萬盛學電腦網

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

JavaScript getDate() 方法詳解:獲取月份中的第幾天

前言

Date.prototype.getDate() 返回 Date 對象中月份的第幾天 (1-31),基於本地時間。本文講解其語法、返回值、常見陷阱及實戰應用。

一、語法與返回值

dateObj.getDate()
  • 參數:無
  • 返回值:1-31 的整數,表示月份中的第幾天
  • 基於本地時間 (非 UTC)

二、基本示例

var dt = new Date("December 25, 1995 23:15:00");
console.log(dt.getDate()); // 25

三、關鍵注意點

1. 與 getDay() 區別 ⚠️

方法含義返回範圍
getDate()月份中的第幾天1-31
getDay()星期幾0-6 (0=周日)

2. 月份邊界行為

var d1 = new Date(2024, 1, 0);  // 2月0天 = 1月最後一天
console.log(d1.getDate()); // 31 (1月31日)

var d2 = new Date(2024, 1, 29); // 2024是閏年
console.log(d2.getDate()); // 29

var d3 = new Date(2023, 1, 29); // 2023非閏年
console.log(d3.getDate()); // 29 (但實際日期是3月1日,月份自動進位)

3. 時區影響

// 假設當前 UTC 時間 2024-01-01 00:30,本地時區 UTC+8
var dt = new Date('2024-01-01T00:30:00Z');
console.log(dt.getDate());     // 1 (本地 1月1日)
console.log(dt.getUTCDate());  // 1 (UTC 也是1日)

// 假設 UTC 2024-01-01 23:30,本地 UTC+8
var dt2 = new Date('2024-01-01T23:30:00Z');
console.log(dt2.getDate());     // 2 (本地已經1月2日)
console.log(dt2.getUTCDate());  // 1 (UTC仍是1月1日)

四、實戰應用

1. 獲取當月天數


function getDaysInMonth(year, month) {
    // month: 1-12
    return new Date(year, month, 0).getDate();
}
console.log(getDaysInMonth(2024, 2)); // 29 (閏年)
console.log(getDaysInMonth(2023, 2)); // 28

2. 日期格式化 (手動拼接)


function formatDate(date) {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
}
console.log(formatDate(new Date())); // "2024-01-15"

3. 判斷是否為月末


function isMonthEnd(date) {
    const nextDay = new Date(date);
    nextDay.setDate(date.getDate() + 1);
    return nextDay.getDate() === 1;
}

五、完整運行示例

<html>
<head><title>JavaScript getDate Method</title></head>
<body>
<script>
    var dt = new Date("December 25, 1995 23:15:00");
    document.write("getDate() : " + dt.getDate());
</script>
</body>
</html>

輸出:getDate() : 25

六、總結

  • getDate() 返回 1-31,表示月份中的第幾天
  • 基於本地時間,跨時區項目注意與 getUTCDate() 區分
  • 構造 Date 時 day=0 可獲取上月最後一天,巧妙計算月天數
  • 配合 padStart() 可輕鬆實現日期格式化
  • 現代項目推薦使用 Intl.DateTimeFormat 或 Temporal API (提案階段) 獲得更強大的國際化支持
copyright © 萬盛學電腦網 all rights reserved