简体   繁体   English

JavaScript 获取月的最后一天 - 基于年、月和日

[英]JavaScript get last day of Month - based on Year, Month and day

I need a JS function to get the last date of the month.我需要一个 JS function 来获取本月的最后一个日期。 as an example, I need to get the last Wednesday of this month.例如,我需要得到本月的最后一个星期三。

I will pass Year, Month and day as a arguments.我将传递年、月和日作为 arguments。

getLastDayOfMonth('2022', '02', 'Wednesday');

function getLastDayOfMonth(year, month, day){

     // Output should be like this

       2022-02-23    

    (this is last Wednesday of the month, according to the arguments- Year, month and Day)
}

Create a Date instance with the last day of the month then work backwards one day at a time until you match the day of the week you're after使用该月的最后一天创建一个Date实例,然后一次向后工作一天,直到您匹配您之后的星期几

 const normaliseDay = day => day.trim().toLowerCase() const dayIndex = new Map([ ["sunday", 0], ["monday", 1], ["tuesday", 2], ["wednesday", 3], ["thursday", 4], ["friday", 5], ["saturday", 6], ]) const getLastDayOfMonth = (year, month, dow) => { const day = dayIndex.get(normaliseDay(dow)) // init as last day of month const date = new Date(Date.UTC(parseFloat(year), parseFloat(month), 0)) // work back one-day-at-a-time until we find the day of the week while (date.getDay().= day) { date.setDate(date.getDate() - 1) } return date } console,log(getLastDayOfMonth("2022", "02", "Wednesday"))

The numeric values are parsed as numbers so we don't run into problems with zero-padded octal numbers.数值被解析为数字,因此我们不会遇到用零填充的八进制数的问题。

You can get the last day of the month then subtract the required number of days based on the difference between the end of month day and required day, eg您可以得到当月的最后一天,然后根据月末日和所需日期之间的差异减去所需的天数,例如

 /* Return last instance of week day for given year and month * @param {number|string} year: 4 digit year * @param {number|string} month: calendar month number (1=Jan) * @param {string} day: English week day name, eg Sunday, * Sun, su, case insensitive * @returns {Date} date for last instance of day for given * year and month */ function getLastDayOfMonth(year, month, day) { // Convert day name to index let i = ['su','mo','tu','we','th','fr','sa'].indexOf(day.toLowerCase().slice(0,2)); // Get end of month and eom day index let eom = new Date(year, month, 0); let eomDay = eom.getDay(); // Subtract required number of days eom.setDate(eom.getDate() - eomDay + i - (i > eomDay? 7: 0)); return eom; } // Examples - last weekdays for Feb 2022 ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'].forEach(day => console.log(day.slice(0,3) + ': ' + getLastDayOfMonth('2022', '02', day).toLocaleDateString('en-GB',{ year:'numeric', month:'short', day:'numeric', weekday:'short' }) ));

In the above:在上面:

new Date(year, month, 0)

leverages the fact that the month is calendar month whereas the date constructor months are 0 indexed, so the above sets the date to the zeroth day of March, which resolves to the last day in February.利用月份是日历月份而日期构造函数月份索引为 0 的事实,因此上面将日期设置为 3 月的第 0 天,即解析为 2 月的最后一天。

The part:那个部分:

eom.getDate() - eomDay + i - (i > eomDay? 7 : 0)

subtracts the eomDay index to get to the prior Sunday, then i adds days to get the required day.减去eomDay索引以到达前一个星期日,然后添加天数以获得所需的日期。 However, if that goes beyond the end of the month (ie i is greater than eomDay so adds more days that eomDay subtracts), it subtracts 7 days.但是,如果超出月末(即i大于eomDay ,因此增加了eomDay减去的天数),它会减去 7 天。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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