我正试图用momentjs 获得一个月的nth
星期五
其中n
在[1,4]
范围内
因此,如果用户提供n为2。然后我需要知道这个月第二个星期五的日期。
以下是我尝试的没有成功的
let startingFrom = new Date("StartDateStringGoesHere");
let n=2;
let nthFriday = moment(startDate).isoWeekday(n); //I can't figure out how to resolve it here
任何想法都将受到真诚的赞赏。
这是一个通用函数,不需要库
function nthWeekdayOfMonth(year, month, nth, dow) {
const d = new Date(year, month - 1, 7 * (nth - 1) + 1);
const w = d.getDay();
d.setDate(d.getDate() + (7 + dow - w) % 7);
return d;
}
// second(2) friday(5)
for (let month = 1; month < 13; month++) {
console.log(nthWeekdayOfMonth(2022, month, 2, 5).toString());
}
// third(3) sunday(0)
for (let month = 1; month < 13; month++) {
console.log(nthWeekdayOfMonth(2022, month, 3, 0).toString());
}
下面是一个在m 中执行此操作的示例函数
// Using moment get all Fridays in a month
const searchDate = moment()
function getNthDay(n, day, startDate){
let daysArray = []
for (let i = 0; i <= startDate.daysInMonth(); i++) {
const currentDay = moment().startOf("month").add(i, "days");
if (currentDay.format('dddd') === day) {
daysArray.push(currentDay);
}
}
return daysArray[n];
}
const nDay = getNthDay(1, 'Friday', searchDate);
console.log(nDay)