Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect weeks calculation in momentjs

I use node.js with moment 2.9.0

var moment = require("moment");
var d = moment.utc([2014, 11, 27]);
var iso = d.toISOString();
var week = d.week();

shows iso = "2014-12-27T00:00:00.000Z" and week is 52.

But if var d = moment.utc([2014, 11, 28]);

iso is 2014-12-28T00:00:00.000Z

week is 1. Why?

Thank you.

like image 754
Ilya Avatar asked Feb 27 '26 09:02

Ilya


1 Answers

The answer can be found in the docs:

The week of the year varies depending on which day is the first day of the week (Sunday, Monday, etc), and which week is the first week of the year.

For example, in the United States, Sunday is the first day of the week. The week with January 1st in it is the first week of the year.

So, week #1 of 2015 (by this function) is:

  • 2014-12-28 (Sunday)
  • 2014-12-29 (Monday)
  • 2014-12-30 (Tuesday)
  • 2014-12-31 (Wednesday)
  • 2015-01-01 (Thursday)
  • 2015-01-02 (Friday)
  • 2015-01-03 (Saturday)

It's also worth mentioning that moment also has the isoWeek function, which conforms to the ISO 8601 week numbering system.

like image 186
Matt Johnson-Pint Avatar answered Mar 02 '26 14:03

Matt Johnson-Pint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!