我正在创建一个日历,我以表格格式打印周。一个要求是,我可以根据某些用户选项在周一或周日开始这几周。我很难使用时刻的isoWeekday方法。
// Start of some date range. Can be any day of the week.
var startOfPeriod = moment("2013-06-23T00:00:00"),
// We begin on the start of the first week.
// Mon Tues Wed Thur Fri Sat Sun
// 20 21 22 23 24 25 26
begin = moment(startOfPeriod).isoWeekday(1); // will pull from user setting
console.log(begin.isoWeekday()); // 1 - all good
// Let's get the beginning of this first week, respecting the isoWeekday
begin.startOf('week');
console.log(begin.isoWeekday()); // 7 - what happened ???
// Get column headers
for (var i=0; i<7; i++) {
console.log(begin.format('ddd')); // I want Monday first!
begin.add('d', 1);
}
编辑我误解了isoWeekday
实际上在做什么。我认为它设置了“一周中的哪一天是一周的第一天”变量(不存在)。它实际上只是改变星期几,就像moment.weekday()
一样,但是使用1-7范围而不是0-6。
答案 0 :(得分:198)
尝试使用begin.startOf('isoWeek');
代替begin.startOf('week');
答案 1 :(得分:9)
答案 2 :(得分:2)
以为我会为未来的窥视添加这个。如果需要,它将始终确保它的星期一也可用于始终确保星期日。对我来说,我总是需要星期一,但本地依赖于正在使用的机器,这是一个简单的解决方法:
var begin = moment().isoWeekday(1).startOf('week');
var begin2 = moment().startOf('week');
// could check to see if day 1 = Sunday then add 1 day
// my mac on bst still treats day 1 as sunday
var firstDay = moment().startOf('week').format('dddd') === 'Sunday' ?
moment().startOf('week').add('d',1).format('dddd DD-MM-YYYY') :
moment().startOf('week').format('dddd DD-MM-YYYY');
document.body.innerHTML = '<b>could be monday or sunday depending on client: </b><br />' +
begin.format('dddd DD-MM-YYYY') +
'<br /><br /> <b>should be monday:</b> <br>' + firstDay +
'<br><br> <b>could also be sunday or monday </b><br> ' +
begin2.format('dddd DD-MM-YYYY');
答案 3 :(得分:2)
这样您就可以设置一周的初始日期。
moment.locale('en', {
week: {
dow: 6
}
});
moment.locale('en');
请务必使用moment().weekday(1);
代替moment.isoWeekday(1)
答案 4 :(得分:1)
对于任何给定的工作日,这是一个更通用的解决方案。 Working demo on jsfiddle
var myIsoWeekDay = 2; // say our weeks start on tuesday, for monday you would type 1, etc.
var startOfPeriod = moment("2013-06-23T00:00:00"),
// how many days do we have to substract?
var daysToSubtract = moment(startOfPeriod).isoWeekday() >= myIsoWeekDay ?
moment(startOfPeriod).isoWeekday() - myIsoWeekDay :
7 + moment(startOfPeriod).isoWeekday() - myIsoWeekDay;
// subtract days from start of period
var begin = moment(startOfPeriod).subtract('d', daysToSubtract);
答案 5 :(得分:-1)
对于那些希望isoWeek
成为默认值的人,您可以修改时刻的行为:
const moment = require('moment');
const proto = Object.getPrototypeOf(moment());
const {startOf, endOf} = proto;
proto.startOf = function(period) {
if (period === 'week') {
period = 'isoWeek';
}
return startOf.call(this, period);
};
proto.endOf = function(period) {
if (period === 'week') {
period = 'isoWeek';
}
return endOf.call(this, period);
};
现在您可以简单地使用someDate.startOf('week')
,而不必担心您会在星期天或不得不考虑是否使用isoweek
或isoWeek
等。
另外,您可以将其存储在const period = 'week'
之类的变量中,并在subtract()
或add()
操作中安全使用,例如moment().subtract(1, period).startOf(period);
。这段时间不是isoWeek
。