获得正确的索引
给定一个年份和月份,我想确定该月的第三个星期五的日期。我如何利用moment.js来确定这个呢?
。October 2015 => 16th October 2015
给定年和月为整数,并假设星期五是您所在地区一周的第五天(星期一是一周的第一天),则可以有:
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");
}
如果您将月和年作为字符串,则可以使用时刻解析函数而不是Object表示法,因此您将有:
var myMonth = moment("October 2015", "MMMM yyyy");
如果星期五不是一周的第五天(索引为4的天),您可以使用moment.weekdays()
根据上面(1和2)的答案,
我对函数进行了一般化,使其可以返回任何给定日期的任何工作日或任何星期。
var getNthWeekday = function(baseDate, weekth, weekday){
// parse base date
var date = moment(baseDate);
var year = date.year();
var month = date.month();
// Convert date to moment (month 0-11)
var myMonth = moment({year: year, month: month});
// assume we won't have to move forward any number of weeks
var weeksToAdvance = weekth-1;
// Get first weekday of the first week of the month
var firstOccurranceOfDay = myMonth.weekday(weekday);
// Check if first weekday occurrance is in the given month
if( firstOccurranceOfDay.month() != month ){
weeksToAdvance++;
}
// Return nth weekday of month formatted (custom format)
return firstOccurranceOfDay.add(weeksToAdvance, 'weeks');
}
基于@VincenzoC.
这允许我发送和接收一个瞬间。
let getThirdFriday: function(mDate) {
// Based on https://stackoverflow.com/a/34278588
// By default we will need to add two weeks to the first friday
let nWeeks = 2,
month = mDate.month();
// Get first Friday of the first week of the month
mDate = mDate.date(1).day(5);
// Check if first Friday is in the given month
// it may have gone to the previous month
if (mDate.month() != month) {
nWeeks++;
}
// Return 3rd Friday of the month formatted (custom format)
return mDate.add(nWeeks, 'weeks');
}
那么我可以这样命名它:
let threeMonth = getThirdFriday(
moment()
.add(3, 'months')
).format("YYYY-MM-DD");