萬盛學電腦網

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

JavaScript 計算當月剩餘天數:從基礎實現到生產級工具函數

計算「本月還剩幾天」是常見需求(如倒計時、配額提醒)。本文從原文簡易腳本出發,演進至生產級工具函數,涵蓋閏年處理、時區陷阱、TypeScript 類型、單元測試與現代 API 替代方案。

一、原文代碼分析與問題

// 原文代碼
var today = new Date();
var now = today.getDate();
var year = today.getYear(); // ⚠️ 已棄用,IE 返回兩位年份
if (year < 2000) year += 1900; // Y2K 修正
var month = today.getMonth(); // 0-11
var monarr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) 
    monarr[1] = 29;
document.write("這個月還剩 " + (monarr[month] - now) + " 天了");

主要問題

  • getYear() 已棄用,應用 getFullYear()
  • document.write 會覆蓋整個文檔,生產環境禁用
  • 無時區處理:用戶跨時區訪問可能導致日期偏差
  • 硬編碼邏輯,不可復用、難測試

二、現代標準實現

1. 核心工具函數(ESM 模組風格)

/**
 * 獲取指定日期所在月份的總天數
 * @param {Date} date 目標日期,默認當前時間
 * @returns {number} 該月總天數 (28-31)
 */
export function getDaysInMonth(date = new Date()) {
    const year = date.getFullYear();
    const month = date.getMonth(); // 0-11
    // 下月 1 日的前一天 = 本月最後一天
    return new Date(year, month + 1, 0).getDate();
}

/**
 * 計算指定日期所在月份剩餘天數(含當天)
 * @param {Date} date 目標日期
 * @returns {number} 剩餘天數
 */
export function getRemainingDaysInMonth(date = new Date()) {
    const total = getDaysInMonth(date);
    const currentDay = date.getDate();
    return total - currentDay + 1; // 含當天
}

/**
 * 計算剩餘天數(不含當天)
 */
export function getRemainingDaysExcludeToday(date = new Date()) {
    return getDaysInMonth(date) - date.getDate();
}

2. 時區安全版本(業務常需「用戶本地時間」或「服務器時間」)


/**
 * 以指定時區計算剩餘天數
 * @param {string} timeZone IANA 時區標識,如 'Asia/Shanghai', 'UTC'
 * @param {Date} baseDate 基準時間,默認當前
 */
export function getRemainingDaysInTimeZone(timeZone, baseDate = new Date()) {
    // 使用 Intl.DateTimeFormat 獲取指定時區的年月日
    const fmt = new Intl.DateTimeFormat('en-CA', { // ISO 格式 YYYY-MM-DD
        timeZone,
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
    const [{value: year},, {value: month},, {value: day}] = fmt.formatToParts(baseDate);
    
    const dateInZone = new Date(`${year}-${month}-${day}T00:00:00`);
    return getRemainingDaysInMonth(dateInZone);
}

三、TypeScript 類型定義

interface DateRangeInfo {
    year: number;
    month: number; // 1-12
    day: number;
    daysInMonth: number;
    remainingDays: number; // 含今日
    remainingDaysExclToday: number;
    progressPercent: number; // 月度進度 0-100
}

export function getMonthProgressInfo(date = new Date(), timeZone?: string): DateRangeInfo {
    const d = timeZone 
        ? parseDateInTimeZone(date, timeZone) 
        : date;
    
    const year = d.getFullYear();
    const month = d.getMonth() + 1;
    const day = d.getDate();
    const daysInMonth = getDaysInMonth(d);
    const remainingDays = daysInMonth - day + 1;
    const remainingDaysExclToday = daysInMonth - day;
    const progressPercent = Math.round((day / daysInMonth) * 10000) / 100;
    
    return { year, month, day, daysInMonth, remainingDays, remainingDaysExclToday, progressPercent };
}

四、單元測試用例

import { describe, it, expect } from 'vitest';
import { getDaysInMonth, getRemainingDaysInMonth, getMonthProgressInfo } from './dateUtils';

describe('月份天數計算', () => {
    it('平年 2 月 28 天', () => {
        expect(getDaysInMonth(new Date(2023, 1, 15))).toBe(28);
    });
    it('閏年 2 月 29 天', () => {
        expect(getDaysInMonth(new Date(2024, 1, 15))).toBe(29);
    });
    it('大月 31 天', () => {
        expect(getDaysInMonth(new Date(2023, 0, 1))).toBe(31); // 1月
        expect(getDaysInMonth(new Date(2023, 11, 1))).toBe(31); // 12月
    });
});

describe('剩餘天數', () => {
    it('月中剩餘天數含今日', () => {
        const d = new Date(2023, 4, 15); // 5月15日,共31天
        expect(getRemainingDaysInMonth(d)).toBe(17); // 31-15+1
    });
    it('月底最後一天剩餘1天', () => {
        expect(getRemainingDaysInMonth(new Date(2023, 1, 28))).toBe(1);
    });
    it('進度百分比', () => {
        const info = getMonthProgressInfo(new Date(2023, 4, 15)); // 5月15日
        expect(info.progressPercent).toBe(48.39); // 15/31*100
    });
});

五、現代 API 替代方案

1. Temporal API (Stage 3,未來標準)


// 即將原生支持
const now = Temporal.Now.plainDateISO(); // 當前日期(含時區)
const daysInMonth = now.daysInMonth;
const remaining = daysInMonth - now.day + 1;

2. date-fns / dayjs 輕量庫

import { daysInMonth, differenceInCalendarDays } from 'date-fns';
// 或
import dayjs from 'dayjs';
dayjs().daysInMonth(); // 當月總天數
dayjs().endOf('month').diff(dayjs(), 'day') + 1; // 剩餘天數含今日

六、UI 集成示例:倒計時組件

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { getMonthProgressInfo } from '@/utils/dateUtils';

const info = ref(getMonthProgressInfo());
let timer;

function update() {
    info.value = getMonthProgressInfo();
}

onMounted(() => {
    update();
    // 每天 00:00:01 更新一次
    const now = new Date();
    const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 1);
    const ms = tomorrow - now;
    setTimeout(() => {
        update();
        timer = setInterval(update, 24 * 60 * 60 * 1000);
    }, ms);
});

onUnmounted(() => clearInterval(timer));
</script>

<template>
  <div class="month-progress">
    <p>本月進度:{{ info.progressPercent }}%</p>
    <div class="bar">
      <div class="fill" :style="{ width: info.progressPercent + '%' }"></div>
    </div>
    <p>剩餘 {{ info.remainingDays }} 天(含今日)</p>
  </div>
</template>

七、總結

  1. 核心技巧:new Date(year, month+1, 0).getDate() 獲取月總天數,巧妙利用日期溢出特性
  2. 棄用 getYear(),統一用 getFullYear()
  3. 封裝純函數,分離計算邏輯與副作用(DOM/網絡)
  4. 考慮時區:全球化產品必須指定業務時區
  5. 引入 date-fns 或 dayjs 替代手寫工具庫,減少維護成本

一個 getRemainingDaysInMonth() 函數,承載著日期邊界、時區、閏年、測試性、可維護性等工程化思考。下次需求來時,直接 import 即用,專業可靠。

copyright © 萬盛學電腦網 all rights reserved