萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 獲取上個月第一天與最後一天的標準方法

核心邏輯

關鍵思路:先獲取本月第一天 00:00:00,再進行月份/日期運算,避免月底日期差異(如 31 號往前推一個月)導致的邏輯錯誤。

工具函數:獲取當月第一天 00:00:00

function getCurrentMonthFirst() {
  var now = new Date();
  return new Date(now.getFullYear(), now.getMonth(), 1); // 時分秒自動為 0
}

獲取上月第一天

function getLastMonthFirst() {
  var firstThisMonth = getCurrentMonthFirst();
  // setMonth 會自動處理跨年(如 1 月 -1 → 去年 12 月)
  return new Date(firstThisMonth.setMonth(firstThisMonth.getMonth() - 1));
}

獲取上月最後一天

function getLastMonthLast() {
  var firstThisMonth = getCurrentMonthFirst();
  // 本月第一天 00:00:00 減 1 毫秒 = 上月最後一天 23:59:59.999
  // 但為了獲取「日期部分」,直接用 setDate(0) 更簡潔:
  // Date 對象的 setDate(0) 表示上月最後一天
  return new Date(firstThisMonth.setDate(0));
}

完整可用工具模組

const DateUtils = {
  // 獲取指定日期所在月的第一天 00:00:00
  getMonthFirst(date = new Date()) {
    return new Date(date.getFullYear(), date.getMonth(), 1);
  },

  // 獲取指定日期所在月的最後一天 23:59:59.999
  getMonthLast(date = new Date()) {
    var nextMonthFirst = new Date(date.getFullYear(), date.getMonth() + 1, 1);
    return new Date(nextMonthFirst.getTime() - 1);
  },

  // 獲取上月第一天
  getLastMonthFirst() {
    return this.getMonthFirst(new Date(new Date().setMonth(new Date().getMonth() - 1)));
  },

  // 獲取上月最後一天
  getLastMonthLast() {
    var firstThisMonth = this.getMonthFirst();
    return new Date(firstThisMonth.setDate(0)); // 等同於上月最後一天 00:00:00
  },

  // 格式化輸出 YYYY-MM-DD
  formatDate(date) {
    var y = date.getFullYear();
    var m = String(date.getMonth() + 1).padStart(2, '0');
    var d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  }
};

// 使用示例
console.log('上月第一天:', DateUtils.formatDate(DateUtils.getLastMonthFirst()));
console.log('上月最後一天:', DateUtils.formatDate(DateUtils.getLastMonthLast()));

關鍵點提示

  • Date 月份是 0-11(0=1月),getDate() 是 1-31。
  • setMonth()、setDate() 會修改原對象並返回時間戳,鏈式調用時注意副作用。
  • new Date(firstThisMonth.setDate(0)) 是獲取上月最後一天的經典技巧(day=0 表示上月最後一天)。
  • 若需「上月最後一天 23:59:59」,用 new Date(firstThisMonth.getTime() - 1)。
  • 時區問題:以上均為本地時間。跨時區業務請使用 UTC 方法(getUTCFullYear 等)或 date-fns/dayjs 庫。

現代替代:使用 dayjs / date-fns

// dayjs (2KB, API 類 moment)
import dayjs from 'dayjs';
const lastMonthFirst = dayjs().subtract(1, 'month').startOf('month');
const lastMonthLast = dayjs().subtract(1, 'month').endOf('month');
console.log(lastMonthFirst.format('YYYY-MM-DD'));
console.log(lastMonthLast.format('YYYY-MM-DD'));

生產環境強烈建議使用成熟日期庫,避免原生 Date 陷阱(時區、夏令時、解析不一致等)。

copyright © 萬盛學電腦網 all rights reserved