a15n
a15n

Reputation: 507

Moment.js: How do you get the difference between two dates in 'quarters'

I am trying to calculate the number of full financial quarters between two dates using momentJS. Unfortunately I don't think that moment has quarter difference handling. Did I miss it or should I make a feature request?

For example, with the following code I'd expect the result to be 1 because the entire first quarter of 2014 (Jan 1 - Mar 31) is contained within those dates.

var beginDate = moment('2013 12 31');
var endDate = moment('2014 04 01');

endDate.diff(beginDate, 'quarters')
// should return 1

With this code I'd expect the result to be 2 because the the first and second quarters of 2014 are contained.

var beginDate = moment('2013 12 31');
var endDate = moment('2014 07 01');

endDate.diff(beginDate, 'quarters')
// should return 2

I tried this but it produces unexpected and often incorrect results.

Math.floor(endDate.diff(beginDate, 'months') / 4)

Any input you have is appreciated. Thanks.

Upvotes: 1

Views: 2483

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241563

There are three months in a quarter. So, this should work:

Math.floor(endDate.diff(beginDate, 'months') / 3)

However, realize this will return the number of whole periods of 3 months each. This may or may not align to the boundaries of a quarter that you are thinking. For example, a period from March through May would be three months but spans across two different quarters.

Upvotes: 0

Lee Taylor
Lee Taylor

Reputation: 7994

Here's my attempt. I use the year and the quarter to create a "compound" number. Then subtract these from each other:

var beginDate = moment("2013-Dec-31");
var endDate = moment("2014-Apr-01");

// Calculate Quarters as the year plus fractional quarter
var beginQ = beginDate.year() + (beginDate.quarters()-1) / 4;
var endQ = endDate.year() + (endDate.quarters()-1) / 4;

document.write(beginQ + "<br />");
document.write(endQ + "<br />");

document.write( (endQ - beginQ) * 4 + "<br />");
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>

Upvotes: 1

Related Questions