JavaScript 中的 Date 物件 用於處理日期和時間。它提供了創建、操作和格式化日期和時間值的方法。
您可以透過多種方式建立 Date 物件:
Method | Description | Example |
---|---|---|
getFullYear() | Returns the year | date.getFullYear() -> 2024 |
getMonth() | Returns the month (0-11) | date.getMonth() -> 10 (November) |
getDate() | Returns the day of the month (1-31) | date.getDate() -> 21 |
getDay() | Returns the weekday (0-6, Sun=0) | date.getDay() -> 4 (Thursday) |
getHours() | Returns the hour (0-23) | date.getHours() -> 10 |
getMinutes() | Returns the minutes (0-59) | date.getMinutes() -> 0 |
getSeconds() | Returns the seconds (0-59) | date.getSeconds() -> 0 |
getTime() | Returns timestamp in milliseconds | date.getTime() -> 1732231200000 |
Method | Description | Example |
---|---|---|
setFullYear(year) | Sets the year | date.setFullYear(2025) |
setMonth(month) | Sets the month (0-11) | date.setMonth(0) -> January |
setDate(day) | Sets the day of the month | date.setDate(1) -> First day of the month |
setHours(hour) | Sets the hour (0-23) | date.setHours(12) |
setMinutes(minutes) | Sets the minutes (0-59) | date.setMinutes(30) |
setSeconds(seconds) | Sets the seconds (0-59) | date.setSeconds(45) |
Method | Description | Example |
---|---|---|
toDateString() | Returns date as a human-readable string | date.toDateString() -> "Thu Nov 21 2024" |
toISOString() | Returns date in ISO format | date.toISOString() -> "2024-11-21T10:00:00.000Z" |
toLocaleDateString() | Returns date in localized format | date.toLocaleDateString() -> "11/21/2024" |
toLocaleTimeString() | Returns time in localized format | date.toLocaleTimeString() -> "10:00:00 AM" |
處理跨區域的日期時請注意時區
。使用Day.js 等函式庫進行高階處理。
以上是JavaScript 日期物件備忘單的詳細內容。更多資訊請關注PHP中文網其他相關文章!