Nicolas
Nicolas

Reputation: 4756

Moment.JS - Get date from week number

I don't see this in the documentation of moment.js. Maybe I'm skipping over it but I want to convert a week number in a year to a date format.

for example

week: number = 13 
year: number = 2017
date: date = // get date format for the first day of that week

I'm using moment.js, but I can't find what I want in the documentation. Is this possible to do? I've found some answers for plain javascript, but since I'm already using moment.js, I figured there might be an easy way to do this

Upvotes: 13

Views: 16311

Answers (5)

gil.fernandes
gil.fernandes

Reputation: 14601

moment.js seems to understand expressions produced by the default HTML input type="week" element, like: 2022-W26.

So you can use moment to convert these expressions into dates, like so:

const weekMoment = moment('2022-W26') // week 26 of year 2022
const weekStart = weekMoment.toDate() // Mon Jun 27 2022 00:00:00 GMT+0100

Like so you do not need to create the date and then add weeks to it. One moment call is enough.

Just another note: for this to work do not forget the pad the week number, e.g: week 1 should be 01, etc. You should always have two digits to represent the week.

Upvotes: 1

ngstschr
ngstschr

Reputation: 2319

No need to add: moment().year(2017).week(13);

Upvotes: 6

Tomasz Rup
Tomasz Rup

Reputation: 859

Yes, it's possible:

var date = moment('2017').add(13, 'weeks');

Note that moment('2017') returns January 1st of 2017.

Upvotes: 18

MGA
MGA

Reputation: 531

Using startOf('isoweek') you will get the first day of the week.

moment('2017').add(13, 'weeks').startOf('week').format('DD MM YYYY'); // "02 04 2017"m, gives you Sunday(last day of the week)

moment('2017').add(13, 'weeks').startOf('isoweek').format('DD MM YYYY');
"27 03 2017"// first day of the week ( gives you Monday)

Upvotes: 6

Andreas
Andreas

Reputation: 21881

Another way is to use a format string

var dateLocale = moment(week + " " + year, "ww gggg");
var dateISO = moment(week + " " + year, "WW GGGG");

Upvotes: 4

Related Questions