Getting the same week for two different weeks - momentjs

Viewed 46

I am getting the same week for these two dates even though they are in different weeks when looking at a calendar. What am I doing wrong?

  moment()
    .set({
      year: 1982,
      month: 3,
      day: 21,
      hour: 0,
    })
    .weeks()

  moment()
    .set({
      year: 1982,
      month: 3,
      day: 26,
      hour: 0,
    })
    .weeks()

Result is 17 for both.

2 Answers

Mar 21 1982 is a Sunday. Mar 26 1982 is Friday. They are in the same week if you are located in US/Canada or any place that has Sunday as the first day of the week. So you are getting the correct result.

See: https://momentjs.com/docs/#/customization/dow-doy/ under the section "First Day of Week and First Week of Year"

// ISO-8601, Europe
moment.updateLocale("en", { week: {
  dow: 1, // First day of week is Monday
  doy: 4  // First week of year must contain 4 January (7 + 1 - 4)
}});

// US, Canada
moment.updateLocale("en", { week: {
  dow: 0, // First day of week is Sunday
  doy: 6  // First week of year must contain 1 January (7 + 0 - 1)
}});

// Many Arab countries
moment.updateLocale("en", { week: {
  dow: 6, // First day of week is Saturday
  doy: 12 // First week of year must contain 1 January (7 + 6 - 1)
}});

// Also common
moment.updateLocale("en", { week: {
  dow: 1, // First day of week is Monday
  doy: 7  // First week of year must contain 1 January (7 + 1 - 1)
}});

Per the Moment.JS 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.

In you're example 1982, the first day of the year was a Friday, so that means every Friday the week number would increment. So even though April 21st and April 26th (which are you're dates respectively) are on different weeks when going from Sunday to Saturday. They are technically the same week due to the locale that Moment.JS is using to establish the week of the year.

Related