【问题标题】:JavaScript get last day of Month - based on Year, Month and dayJavaScript 获取月的最后一天 - 基于年、月和日
【发布时间】:2022-01-19 05:35:36
【问题描述】:

我需要一个 JS 函数来获取该月的最后一个日期。 例如,我需要得到本月的最后一个星期三。

我将传递年、月和日作为参数。

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)
}

【问题讨论】:

标签: javascript node.js date


【解决方案1】:

使用该月的最后一天创建一个 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"))

数值被解析为数字,因此我们不会遇到零填充的八进制数字问题。

【讨论】:

  • 它正在工作,兄弟。非常感谢兄弟。
【解决方案2】:

您可以得到当月的最后一天,然后根据月末日期和所需日期之间的差异减去所需的天数,例如

/* 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, e.g. 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 增加天数以获得所需的日期。但是,如果超出月末(即,i 大于 eomDay,因此增加了 eomDay 减去的更多天数),它会减去7 天。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    相关资源
    最近更新 更多