Last active
August 20, 2017 15:43
-
-
Save patrickocoffeyo/7991099 to your computer and use it in GitHub Desktop.
Year period management for moment.js. Requires the moment.js library. Default period is the standard US year divided into quarters.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| moment.fn.periodStartDates = [ | |
| {month: 0, day: 1} | |
| {month: 3, day: 1} | |
| {month: 6, day: 1} | |
| {month: 9, day: 1} | |
| ] | |
| moment.fn.period = -> | |
| period = Math.floor(this.month() / this.periodStartDates.length) | |
| start = moment(_.extend(this.periodStartDates[period], {year: this.year()})) | |
| end = moment(_.extend(this.periodStartDates[(period + 1) % this.periodStartDates.length], {year: this.year()})).subtract('millisecond', 1) | |
| if start > this then start.subtract('year', 1) else if end < this then end.add('year', 1) | |
| return {start: start, end: end} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 9 should have
Math.floorinstead ofMath.ceil.this.month()returns a 0-based month index, and theperiodStartDatesarray has a 0-based indexMarch (2) divided by
this.periodStartDates.length(4) equals 0.5 and should be floored to 0 to be in the period that begins on January 1.Ran into this bug in some old code we still have in production :-)