3

I'm trying to get the weeknumer of a date, but I want it to work with a variable first day of the week. A user is able to set the first day of the week. I couldn't find a javascript solution, so I tried moment. Unfortunately, I couldn't find a way to set the first day of the week. E.g. Sunday for US, Monday for the EU, but it would be nice if it could be any other day as well.

Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116

1 Answers1

4

Moment supports i18n, you can change locale globally or change locales locally and update first day of the week according locale rules. Then you can use week() that:

Gets or sets the week of the year.

Because different locales define week of year numbering differently, Moment.js added moment#week to get/set the localized week of the year.

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.

Here a example showing how the same day (e.g. 2017-08-13) has different week value using different locales:

moment.locale('en');
var now2 = moment('2017-08-13');
console.log( now2.week() ); // 33

moment.locale('it');
var now1 = moment('2017-08-13');
console.log( now1.week() ); // 32
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

If you don't want to change moment locale, you can simply customize the first day of the week (for the current locale) using updateLocale method, just change the value of dow (day of week) key (and doy key too, if needed) of the week object. See Customize section of the docs to get more info about locale customization.

Here a live example:

var now1 = moment('2017-08-13');
console.log( now1.week() ); // 33

moment.updateLocale('en', {
  week: {
    dow : 1, // Monday is the first day of the week.
  }
});

var now2 = moment('2017-08-13');
console.log( now2.week() ); // 32
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
VincenzoC
  • 30,117
  • 12
  • 90
  • 112