Search code examples
javascriptmomentjsunix-timestamp

How to use Moment.js to determine financial quarters based upon Unix timestamp?


My goal is to compare two data sets representing financial quarters. The quirks of the API require two dates per get request: startDate (inclusive) and endDate (exclusive). Therefore, e.g., to get data for the month of July 2016 you need:

startDate = 20160701 and endDate = 20160801.

Given a single unixStartDate (which is a Unix timestamp), I want to find (1) the startDate and endDate for the current quarter, and (2) the startDate and endDate for the previous quarter.

So far I can use moment.js to determine the current quarter without issue:
const currentQuarter = moment.unix(unixStartDate).utc().quarter();
I could probably make a hacky switch-case based on that information, but I'm hoping for a more elegant solution.

Moment.js also contains moment().startOf('quarter'), but I've been unable to figure out its proper usage. Console.log yields an object:

Moment {_isAMomentObject: true, 
_isUTC: false, 
_pf: Object, 
_locale: Locale, 
_d: Fri Jul 01 2016 00:00:00 GMT-1000 (HST)…}

Solution

  • Here's a verbose version:

    const moment = require('moment');
    
    let unixStartDate  = ...;
    
    let current        = moment(unixStartDate);
    let currentStartOf = moment(current).startOf('quarter');
    let currentEndOf   = moment(current).  endOf('quarter').add(1, 'day');
    
    let previous        = moment(current).subtract(1, 'quarter');
    let previousStartOf = moment(previous).startOf('quarter');
    let previousEndOf   = moment(previous).  endOf('quarter').add(1, 'day');
    
    console.log(
      'current ', 
      currentStartOf.format('YYYYMMDD'),
      currentEndOf  .format('YYYYMMDD')
    )
    
    console.log(
      'previous', 
      previousStartOf.format('YYYYMMDD'),
      previousEndOf  .format('YYYYMMDD')
    )