[英]End date of the week for the current month
我每周(比如說,星期五)生成一份報告,我需要每個月的周末日期。 如果它是一個新的月份,則返回該月的最后一個日期.. 我在這里得到第一個日期:-
var firstDay = new Date(date.getFullYear(), date.getMonth(), 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;
}
嘗試使用下面的 function。
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()));
查看RRule package。 它為您提供了很多日期和時間間隔的可能性。 它適用於日歷中的規則。
對於你的情況。 每周五:
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)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.