Determine third Friday of the month given month an

2019-01-27 03:25发布

Given a year and month, I'd like to determine the date of the third Friday of that month. How would I leverage moment.js to determine this?

E.g. October 2015 => 16th October 2015

标签: date momentjs
1条回答
Lonely孤独者°
2楼-- · 2019-01-27 04:10

Given year and month as integers and assuming that Friday is the fifth day of the week in your locale (Monday is the first day of the week), you can have:

function getThirdFriday(year, month){
    // Convert date to moment (month 0-11)
    var myMonth = moment({year: year, month: month});
    // Get first Friday of the first week of the month
    var firstFriday = myMonth.weekday(4);
    var nWeeks = 2;
    // Check if first Friday is in the given month
    if( firstFriday.month() != month ){
        nWeeks++;
    }
    // Return 3rd Friday of the month formatted (custom format)
    return firstFriday.add(nWeeks, 'weeks').format("DD MMMM YYYY");
}

If you have month and year as a string, you can use moment parsing functions instead of the Object notation, so you will have:

var myMonth = moment("October 2015", "MMMM yyyy");

If Friday is not the fifth day of the week (day with index 4), you can get the correct index using moment.weekdays()

查看更多
登录 后发表回答