[英]Get the First Weekday of the Month with moment.js
我有一些使用moment.js(这是一个要求)获取每月第一个工作日的代码,如下所示:
dateStart: function() {
var first = moment().startOf('month');
switch(first.day()) {
case 6:
return first.add(2, 'days');
case 0:
return first.add(1, 'days');
default:
return first;
};
}
有没有更好的方法来做到这一点?
如果第一天是星期天或星期六( first.day() % 6 === 0
)然后返回下一个星期一( first.day(1)
):
function dateStart() {
var first = moment().startOf('month');
return first.day() % 6 === 0 ? first.add(1, 'day').day(1) : first;
}
正如评论中提到的那样first.day(1)
可以返回上个月的星期一。 如果一个月的第一天是星期六,就会发生这种情况。 为确保您从当月的一周中获得星期一,只需将周末日期加 1。
有趣的问题。 我想你只需要得到一个月的第一天,然后添加天数直到这一天是工作日。 看看: https : //jsfiddle.net/4rfrg4c0/2/
function get_first_working_day (year, month) {
// get the first day of the specified month and year
var first_working_day = new moment([year, month])
// add days until the day is a working day
while (first_working_day.day() % 6 == 0) {
first_working_day = first_working_day.add(1, 'day')
}
// return the day
return first_working_day
}
// tests
$('.september').append(get_first_working_day(2016, 8).format('dddd, MMMM Do YYYY'))
$('.october').append(get_first_working_day(2016, 9).format('dddd, MMMM Do YYYY'))
尝试使用这个:
const currentDate = moment(Date.now);
const dayOfMonth = currentDate.date();
const dayOfWeek = currentDate.weekday();
//check if its the first 3 days of the month
if (dayOfMonth >= 1 && dayOfMonth <= 3) {
//check if its the first of the month and also a weekday
if (dayOfMonth === 1 && dayOfWeek >= 1 && dayOfWeek <= 5) {
//set your conditions here
}
//check if its the 2nd/3rd of the month and also a weekday, if the the 1st/2nd was //on a weekend
if ((dayOfMonth === 2 || dayOfMonth === 3) && dayOfWeek === 1) {
//set your conditions here
}
}
抱歉,如果您想要下个月的第一个星期一 = 月 +1,那么您的解决方案都不是很令人满意。这样做(但您可以使用 xxx
let first = moment().startOf('month').add(1, 'month'); let day = first; if ( first.day() > 1 ) { day = first.add(8 - first.day(), 'day'); } if ( day.day() === 0 ) { day = day.add(1, 'days'); } date = day.format('YYYY-MM-DD');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.