用moment.js获取本月的第一个工作日

时间:2016-09-12 08:20:22

标签: javascript momentjs

我有一些代码可以使用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;
    };
}

有更好的方法吗?

4 个答案:

答案 0 :(得分:2)

如果第一天是星期日或星期六(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即可。

答案 1 :(得分:1)

尝试使用此:

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

答案 2 :(得分:0)

有趣的问题。我想你只需要在这个月的第一天,然后再添加几天,直到这一天是一个工作日。看看: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'))

答案 3 :(得分:0)

对不起,但您的解决方案都不令人满意 如果您要下个月的第一个星期一=月份+1。 这样做(但是您可以使用xxx转换吗?zzz:yyy;符号,为了便于阅读,我将其保留为经典)

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'); 

  

相关问题