Peter
Peter

Reputation: 407

Determine first day of a week by a given date in moment js

I want to determine the first day of a week by a given date in Moment.js. This is my code:

var begin = moment("2015-08-15").startOf('week').isoWeekday(0);
console.log(begin);
var end = moment("2015-08-15").endOf('week').isoWeekday(0);
console.log(end);

I get the following output:

Object { _isAMomentObject: true, _i: "2015-08-15", _f: "YYYY-MM-DD", _isUTC: false, _pf: Object, _locale: Object, _d: Date 2015-08-01T22:00:00.000Z }
Object { _isAMomentObject: true, _i: "2015-08-15", _f: "YYYY-MM-DD", _isUTC: false, _pf: Object, _locale: Object, _d: Date 2015-08-09T21:59:59.999Z }

According to the docs the local is 'en' by default and this would mean that first day of week is Sunday. In my opinion the correct result should be:

begin = 2015-08-09
end = 2015-08-15

When I changed isoWeekday from '0' to '1' the result looks like this:

Object { _isAMomentObject: true, _i: "2015-08-15", _f: "YYYY-MM-DD", _isUTC: false, _pf: Object, _locale: Object, _d: Date 2015-08-02T22:00:00.000Z }
Object { _isAMomentObject: true, _i: "2015-08-15", _f: "YYYY-MM-DD", _isUTC: false, _pf: Object, _locale: Object, _d: Date 2015-08-10T21:59:59.999Z }

This is also wrong. The correct answer would be:

begin = 2015-08-10
end = 2015-08-16

Upvotes: 1

Views: 3392

Answers (2)

Peter
Peter

Reputation: 407

The correct answer will be:

var begin = moment().subtract(1, 'week').startOf('week').format("YYYY MM DD");
var end = moment().subtract(1, 'week').endOf('week').format("YYYY MM DD");

Thanks to help by @MattJohnson

Upvotes: 4

punund
punund

Reputation: 4421

What's going on is that you are getting startOf() your local week of 2015-08-15, which is Sunday 2015-08-09, and then your are resetting this ISO week, which is Monday to Sunday, to its first day, which is of course Monday 2015-08-02.

You need to use startOf('isoWeek') for consistent behaviour.

Upvotes: 1

Related Questions