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.
-
Kindly post a code snippet to work on. – Gopalkrishna Narayan Prabhu Aug 19 '17 at 18:23
-
1A snippet of what? The initialisation of a moment object?? – Robin Dijkhof Aug 19 '17 at 18:28
-
Possible duplicate of [Moment.js get the week number based on a specific day (also past years)](https://stackoverflow.com/questions/25953551/moment-js-get-the-week-number-based-on-a-specific-day-also-past-years) – lumio Aug 19 '17 at 18:51
-
@lumio unfortunately it isn't. In the your link it is not possible to set the first day of the week. – Robin Dijkhof Aug 19 '17 at 18:58
-
What do you mean by "set the first day of the week". You mean you want to change if Sunday or Monday is the first day? Or like actually setting a date – lumio Aug 19 '17 at 18:59
-
@lumio Indeed change it to sunday of monday. Athough it would be nice if it could be any other day. – Robin Dijkhof Aug 19 '17 at 19:00
1 Answers
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>

- 30,117
- 12
- 90
- 112