简体   繁体   中英

Get the First Weekday of the Month with moment.js

I have some code that gets the first weekday of the month using moment.js (that is a requirement) which looks like this:

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

Is there a better way of doing this?

If the first day is sunday or saturday ( first.day() % 6 === 0 ) then return next monday ( first.day(1) ):

function dateStart() {
  var first = moment().startOf('month');
  return first.day() % 6 === 0 ? first.add(1, 'day').day(1) : first;
}

As mentioned in comments first.day(1) can return monday in previous month. This can happen if the first day of the month is saturday. To be sure you get monday from the week in current month just add 1 to the weekend date.

Interesting question. I guess you just have to get the first day of the month and then add days until the day is a working day. Check it out: 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'))

Try using this:

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

Sorry but none of your solutions are quite satisfying if you want the first monday of the next month = month +1.. Do this (but you can convert using xxx? zzz:yyy; notation, I kept it with classic if for readibility)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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