Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

date - Determine third Friday of the month given month and year

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...