30秒学会 JavaScript 片段 · 2023年1月5日

30秒学会 JavaScript 片段 – Last date of month

Returns the string representation of the last date in the given date’s month.

  • Use Date.prototype.getFullYear(), Date.prototype.getMonth() to get the current year and month from the given date.
  • Use the Date constructor to create a new date with the given year and month incremented by 1, and the day set to 0 (last day of previous month).
  • Omit the argument, date, to use the current date by default.

代码实现

const lastDateOfMonth = (date = new Date()) => {
  let d = new Date(date.getFullYear(), date.getMonth() + 1, 0);
  return d.toISOString().split('T')[0];
};

lastDateOfMonth(new Date('2015-08-11')); // '2015-08-30'

翻译自:https://www.30secondsofcode.org/js/s/last-date-of-month