Moment.js - Starting the week on Monday with isoWeekday()

匿名 (未验证) 提交于 2019-12-03 01:55:01

问题:

I'm creating a calendar where I print out weeks in a tabular format. One requirement is that I be able to start the weeks either on Monday or Sunday, as per some user option. I'm having a hard time using moment's isoWeekday method.

// 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

jsFiddle

EDIT I misunderstood what isoWeekday was actually doing. I thought it set the "which day of the week is the first day of the week" variable (that doesn't exist). What it actually does is simply changes the day of the week, just like moment.weekday(), but uses a 1-7 range instead of the 0-6.

回答1:

try using begin.startOf('isoWeek'); instead of begin.startOf('week');



回答2:

Call startOf before isoWeekday.

var begin = moment(date).startOf('week').isoWeekday(1);

Working demo



回答3:

thought I would add this for any future peeps. It will always make sure that its monday if needed, can also be used to always ensure sunday. For me I always need monday, but local is dependant on the machine being used, and this is an easy fix:

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 = 'could be monday or sunday depending on client: 
' + begin.format('dddd DD-MM-YYYY') + '

should be monday:
' + firstDay + '

could also be sunday or monday
' + begin2.format('dddd DD-MM-YYYY');


回答4:

Here is a more generic solution for any given weekday. 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);


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!