Skip to content

Instantly share code, notes, and snippets.

@patrickocoffeyo
Last active August 20, 2017 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickocoffeyo/7991099 to your computer and use it in GitHub Desktop.
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.
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}
@patrickocoffeyo
Copy link
Author

Requires underscore.

@RobertBolender
Copy link

Line 9 should have Math.floor instead of Math.ceil.

this.month() returns a 0-based month index, and the periodStartDates array has a 0-based index

March (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 :-)

@patrickocoffeyo
Copy link
Author

@awesomebob Good catch, thank you! This is super old :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment