繁体   English   中英

当月的一周结束日期

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM