Marcel Hinderlich
Marcel Hinderlich

Reputation: 213

Get the weeks starting and ending date from year and calendar week with javascript

I need to get the weeks starting and ending date with Javascript/ moment.js

As input i have two values: year and week, which is the isoweek of moment.js

year = '2016' week = '1'

should give me the 04.01.2016 and 10.01.2016

where the date has the german format moment().format('DD.MM.YYYY');

Upvotes: 2

Views: 1184

Answers (2)

opus131
opus131

Reputation: 2036

The solution from your comment will produce an incorrect result on 01.01.2017:

moment([2017,0,1]).year(2017).isoWeek(1).startOf('isoweek').format('DD.MM.YYYY');
// = '04.01.2016'

This one is more stable:

//var year = 2016;
//var week = 1;
var startDate = moment([year, 5, 30]).isoWeek(week).startOf('isoweek'); 
var endDate = moment(startDate).endOf('isoweek');
startDate.format('DD.MM.YYYY'); // = '04.01.2016'
endDate.format('DD.MM.YYYY'); // = '10.01.2016'

Explanation: if you initialize the moment instance with a date from week 53 of the previous year in conjunction with isoWeek or week, the year component of that moment instance is set to the previous year. All additional moment methods then operate on the "wrong" year. Therefore use moment([year, 5, 30]) to initialize the moment instance. Any other day after the Jan 3rd works for 2016 too of course, only the few days that belong to week 53 of the previous year cause that problem.

Upvotes: 3

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241535

moment([2016]).isoWeek(1).startOf('isoWeek').format('DD.MM.YYYY')  // "02.01.2015"

Upvotes: 1

Related Questions