簡體   English   中英

JavaScript 獲取月的最后一天 - 基於年、月和日

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

我需要一個 JS function 來獲取本月的最后一個日期。 例如,我需要得到本月的最后一個星期三。

我將傳遞年、月和日作為 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)
}

使用該月的最后一天創建一個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"))

數值被解析為數字,因此我們不會遇到用零填充的八進制數的問題。

您可以得到當月的最后一天,然后根據月末日和所需日期之間的差異減去所需的天數,例如

 /* 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' }) ));

在上面:

new Date(year, month, 0)

利用月份是日歷月份而日期構造函數月份索引為 0 的事實,因此上面將日期設置為 3 月的第 0 天,即解析為 2 月的最后一天。

那個部分:

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

減去eomDay索引以到達前一個星期日,然后添加天數以獲得所需的日期。 但是,如果超出月末(即i大於eomDay ,因此增加了eomDay減去的天數),它會減去 7 天。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM