我每周(例如星期五)生成报告,我需要每个月的结束日期。如果是新月,则返回该月的最后日期。 我在这里第一次约会:-
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
但无法继续。
答案 0 :(得分:1)
JavaScript并没有直接提供获取此类信息的功能,但是您可以自行计算,例如,计算每月的最后一个星期五,例如
function lastFridayOfMonth(year, month) {
// if month will start from one not from 0 then we will have month + 1
var lastDay = new Date(year, month + 2, 0);
var lastDayNumber = 5;
if(lastDay.getDay() < lastDayNumber) {
lastDay.setDate(lastDay.getDate() - 7);
}
lastDay.setDate(lastDay.getDate() - (lastDay.getDay() - lastDayNumber));
return lastDay;
}
答案 1 :(得分:1)
尝试使用以下功能。
function getWeekEndDates(date) {
let year = date.getFullYear();
let month = date.getMonth();
let firstDay = new Date(year, month, 1);
let lastDay = new Date(year, month + 1, 0);
let weekEnds = [];
let dateFriday = firstDay;
if (firstDay.getDay() !== 5) {
dateFriday = new Date(year, month, 1 + ((12 - firstDay.getDay()) % 7));
weekEnds.push(firstDay);
}
while (dateFriday.getMonth() === month) {
weekEnds.push(dateFriday);
dateFriday = new Date(year, month, dateFriday.getDate() + 7);
}
if (lastDay.getDay() !== 5) {
weekEnds.push(lastDay);
}
return weekEnds;
}
getWeekEndDates(new Date()).forEach(x => console.log(x.toDateString()));
getWeekEndDates(new Date(2020, 0, 1)).forEach(x => console.log(x.toDateString()));
getWeekEndDates(new Date(2021, 0, 1)).forEach(x => console.log(x.toDateString()));
答案 2 :(得分:0)
签出RRule软件包。它为您提供了日期和时间间隔的多种可能性。它适用于日历等规则。
根据您的情况。每个星期五:
import { RRule } from 'rrule'
const rule = new RRule({
freq: RRule.WEEKLY,
interval: 1,
byweekday: [RRule.FR],
})
// fridays in interval, you will got an array of dates
rule.between(new Date(Date.UTC(2012, 7, 1)), new Date(Date.UTC(2012, 8, 1)))