Logan_Dupont
Logan_Dupont

Reputation: 275

How to get first date of the week based on week number and year in Moment.js?

I tried to get the start date of a specific week in Moment.js from the week number and year by doing moment().year(...).isoWeek(...).startOf('isoWeek')

But It seems that this function is not always returning the correct date. For example when I live in England and a week always starts on a monday. We should get 31 Dec 2018 when we ask for the first day of week 1, 2019.

This wasn't the case on 31 Dec 2018 as the result I received was 30 Dec 2019 as the begin date of week 1, 2019. See example

Upvotes: 3

Views: 4671

Answers (2)

Logan_Dupont
Logan_Dupont

Reputation: 275

I think I found the solution I was looking for

moment() .isoWeekYear(year) .isoWeek(week) .startOf('week')

Upvotes: 6

VincenzoC
VincenzoC

Reputation: 31482

Please note that, as i18n section of the docs states:

By default, Moment.js comes with English (United States) locale strings. If you need other locales, you can load them into Moment.js for later use.

So if you want to use en-gb locale you have explicitly load it (in the browser, you can use en-gb.js file or moment-with-locales.js and then set locale using moment.locale('en-gb')).

You don't have to use year() setter, because it sets the year to 2019 and moment().year(2019).isoWeek(1) gives you the first isoweek of the 2020. You can create a moment object for a given year using moment({y: year}) instead.

You have to use week() instead of isoWeek if you want locale dependent results:

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 full code sample:

// Set locale to British English
moment.locale('en-gb');
var year = 2019;
var firstMonday = moment({y: year}) // get first day of the given year
    .week(1) // get the first week according locale
    .startOf('week'); // get the first day of the week according locale
// Show result
console.log(firstMonday.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment-with-locales.min.js"></script>

You can use format() to display the value of a moment object.

Upvotes: 0

Related Questions