3

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.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
Ilya
  • 71
  • 1
  • 7

2 Answers2

6

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.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • 1
    var d = moment.utc([2014, 11, 28]).isoWeek(); -> 52 and var d = moment.utc([2014, 11, 29]).isoWeek(); -> 1 isoWeek works incorrectly too? – Ilya Jan 21 '15 at 18:45
  • They both work correctly. ISO Weeks start on Monday, as described in the third paragraph of [the Wikipedia article](http://en.wikipedia.org/wiki/ISO_week_date). I think perhaps you're just confused about the fact that a year's first week could actually start in the prior year. – Matt Johnson-Pint Jan 21 '15 at 19:11
  • Hi @MattJohnson ! I want to start week from thursday because of my project requirement. Is there any way to start week from thursday? so that first date of week#1 can be 2017-01-05 ? – user2899728 Jul 08 '17 at 12:06
  • @user2899728 yes, see the moment docs on customizing locale dow/doy. – Matt Johnson-Pint Jul 08 '17 at 19:53
0

I had this problem too, and it was not week() that helped, but isoWeek()

for me I get week number like this

moment('2022-12-26', 'YYYY-MM-DD').isoWeek() // return 52

moment('2022-12-26', 'YYYY-MM-DD').week() // return 53

Andran
  • 299
  • 1
  • 7