Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js thinks that 2013-12-31 is week 1, not week 53

The moment.js library is awesome, and I use it almost all the time, but I recently ran into something interesting. I'm trying to plot data by week of the year, and one of the data points was 2013-12-31, moment.js tells me this is week 1? Is there a better way to handle this? either with 53, null, -1, or something?

moment('2013-12-31').week()
(returns) 1

I thought maybe using isoWeek or format would get around this, but they all return the same value of 1, despite the documentation saying it goes to 53.

moment('2013-12-31').isoWeek()
(returns) 1
+moment('2013-12-31').format('w')
(returns) 1   

Anyone have any ideas on this? (short of making a test whether the week computed has a min/max date that covers the date value I passed it)

like image 372
Mark Avatar asked Sep 02 '14 20:09

Mark


3 Answers

It is because the week from the 30th december 2013 is considered to be the 1st week of 2014 as you may see on this page epoch converter

And according to momentjs documentation:

The week with January 1st in it is the first week of the year.

like image 75
Adlen Afane Avatar answered Nov 02 '22 13:11

Adlen Afane


I had a problem at my work where we used .format('YYYY WW') for some comparison logic.

That doesn't really make sense, as you should probably use .format('gggg WW') in such cases.

moment('2013-12-31').format('YYYY w'); // Returns 2013 1
moment('2013-12-31').format('gggg w'); // Returns 2014 1

https://momentjs.com/docs/#/displaying/format/

like image 40
Roberto Zvjerković Avatar answered Nov 02 '22 12:11

Roberto Zvjerković


This is expected behavior. According to the ISO 8601 standard, 2013 is not a year with 53 weeks.

The long years, with 53 weeks in them, can be described by any of the following equivalent definitions:

  • any year starting on Thursday (dominical letter D or DC) and any leap year starting on Wednesday (ED)
  • any year ending on Thursday (D, ED) and any leap year ending on Friday (DC)
  • years in which 1 January and 31 December (in common years) or either (in leap years) are Thursdays

(source)

2013 started and ended on a Tuesday so therefore it is not a "long year" and 2013-12-31 is considered part of the first week of 2014.

If you want that week to be the 53rd, you'll have to write custom code for it as the ISO standard won't agree with you!

like image 42
dee-see Avatar answered Nov 02 '22 14:11

dee-see