简体   繁体   English

通过时刻js中的给定日期确定一周的第一天

[英]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. 我想通过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. 根据文档,本地默认为“ en”,这意味着每周的第一天为星期日。 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: 当我将isoWeekday从'0'更改为'1'时,结果如下所示:

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

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 感谢@MattJohnson的帮助

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. 发生的情况是您将startOf()为2015-08-15的本地周,即2015-08-09,然后将ISO周 (即周一至周日)重置为第一天,当然是2015年8月2日星期一。

You need to use startOf('isoWeek') for consistent behaviour. 您需要使用startOf('isoWeek')以获得一致的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM