鉴于一年零一个月,我想确定该月第三个星期五的日期。我如何利用moment.js来确定这个?
E.g。 October 2015 => 16th October 2015
答案 0 :(得分:2)
将年份和月份作为整数并假设星期五是您所在地区的星期五(星期一是一周的第一天),您可以:
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");
}
如果您将月份和年份作为字符串,则可以使用moment parsing functions代替对象表示法,因此您将拥有:
var myMonth = moment("October 2015", "MMMM yyyy");
如果星期五不是一周中的第五天(索引为4的那一天),您可以使用moment.weekdays()
答案 1 :(得分:1)
我对该函数进行了广义化,因此它可以返回给定日期的任何工作日或任何一周。
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');
}
答案 2 :(得分:0)
基于@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");