问题描述
鉴于一年零一个月,我想确定该月的第三个星期五的日期.我将如何利用moment.js来确定这一点?
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?
例如October 2015 => 16th October 2015
推荐答案
将年份和月份指定为整数,并假设星期五是您所在地区的一周的第五天(星期一是一周的第一天),则可以有:
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");
如果星期五不是一周的第五天(索引号为4的日期),则可以使用moment.weekdays()
If Friday is not the fifth day of the week (day with index 4), you can get the correct index using moment.weekdays()
这篇关于确定给定月份和年份的月份的第三个星期五的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!