JavaScript?Date對象之獲取日期、時間與年份完全指南
一、Date 對象基礎
JavaScript 的 Date 對象是處理日期和時間的內(nèi)置對象,它可以表示從 1970 年 1 月 1 日 UTC(協(xié)調(diào)世界時)至今的毫秒數(shù)。
創(chuàng)建 Date 實例
// 1. 獲取當前日期和時間 const now = new Date(); // 2. 通過時間戳創(chuàng)建 const timestamp = 1634567890123; // 毫秒數(shù) const dateFromTimestamp = new Date(timestamp); // 3. 通過日期字符串創(chuàng)建 const dateFromString = new Date("2023-10-20T14:30:00"); // 4. 通過年、月、日等參數(shù)創(chuàng)建 // 注意:月份是從0開始計數(shù)的(0=一月,11=十二月) const specificDate = new Date(2023, 9, 20, 14, 30, 0);
二、獲取當前日期和時間
1. 獲取完整日期時間字符串
const now = new Date(); // 1. 本地日期時間字符串 console.log(now.toString()); // 示例輸出: "Fri Oct 20 2023 14:30:45 GMT+0800 (中國標準時間)" // 2. ISO 格式字符串 console.log(now.toISOString()); // 示例輸出: "2023-10-20T06:30:45.000Z" // 3. 本地日期字符串 console.log(now.toDateString()); // 示例輸出: "Fri Oct 20 2023" // 4. 本地時間字符串 console.log(now.toTimeString()); // 示例輸出: "14:30:45 GMT+0800 (中國標準時間)" // 5. 本地化格式 console.log(now.toLocaleString()); // 示例輸出: "2023/10/20 14:30:45" console.log(now.toLocaleDateString()); // 示例輸出: "2023/10/20" console.log(now.toLocaleTimeString()); // 示例輸出: "14:30:45"
2. 獲取各個日期時間組件
const now = new Date(); // 獲取年份(4位數(shù)) const fullYear = now.getFullYear(); // 2023 // 獲取月份(0-11) const month = now.getMonth(); // 9 (表示十月) // 獲取日期(1-31) const date = now.getDate(); // 20 // 獲取星期(0-6,0表示星期日) const day = now.getDay(); // 5 (表示星期五) // 獲取小時(0-23) const hours = now.getHours(); // 14 // 獲取分鐘(0-59) const minutes = now.getMinutes(); // 30 // 獲取秒數(shù)(0-59) const seconds = now.getSeconds(); // 45 // 獲取毫秒(0-999) const milliseconds = now.getMilliseconds(); // 0 // 獲取時間戳(自1970年1月1日以來的毫秒數(shù)) const timestamp = now.getTime(); // 1697783445000
三、獲取當前年份的多種方式
1. 基本方法
const currentYear = new Date().getFullYear(); console.log(currentYear); // 2023
2. 其他獲取年份的方法
const now = new Date(); // 方法1: getFullYear() (推薦) const year1 = now.getFullYear(); // 2023 // 方法2: 從ISO字符串中提取 const year2 = now.toISOString().slice(0, 4); // "2023" // 方法3: 使用Intl.DateTimeFormat const year3 = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(now); // "2023" // 方法4: 從本地化字符串中提取 const year4 = now.toLocaleDateString('zh-CN', { year: 'numeric' }); // "2023" // 不推薦的方法: getYear() (已廢棄) const yearOld = now.getYear(); // 123 (2023-1900)
四、日期格式化實用技巧
1. 自定義格式化函數(shù)
function formatDate(date) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } console.log(formatDate(new Date())); // "2023-10-20"
2. 格式化為更易讀的形式
function formatNiceDate(date) { const months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']; return `${date.getFullYear()}年 ${months[date.getMonth()]} ${date.getDate()}日`; } console.log(formatNiceDate(new Date())); // "2023年 十月 20日"
3. 相對時間顯示
function timeAgo(date) { const now = new Date(); const seconds = Math.floor((now - date) / 1000); if (seconds < 60) return `${seconds}秒前`; if (seconds < 3600) return `${Math.floor(seconds/60)}分鐘前`; if (seconds < 86400) return `${Math.floor(seconds/3600)}小時前`; const days = Math.floor(seconds/86400); return days < 30 ? `${days}天前` : formatDate(date); } console.log(timeAgo(new Date(Date.now() - 5000))); // "5秒前" console.log(timeAgo(new Date(Date.now() - 3600000))); // "1小時前" console.log(timeAgo(new Date(2023, 9, 1))); // "2023-10-01"
五、時區(qū)處理
1. 獲取UTC時間
const now = new Date(); // 獲取UTC時間組件 const utcHours = now.getUTCHours(); const utcMinutes = now.getUTCMinutes(); // 轉(zhuǎn)換為UTC字符串 console.log(now.toUTCString()); // "Fri, 20 Oct 2023 06:30:45 GMT"
2. 時區(qū)轉(zhuǎn)換
function convertTimezone(date, timezone) { return new Date(date.toLocaleString('en-US', { timeZone: timezone })); } // 將當前時間轉(zhuǎn)換為紐約時間 const nyTime = convertTimezone(new Date(), 'America/New_York'); console.log(nyTime.toLocaleString()); // "10/20/2023, 2:30:45 AM" (假設北京時間是14:30)
六、日期計算
1. 日期加減
// 加5天 const date = new Date(); date.setDate(date.getDate() + 5); // 減3個月 date.setMonth(date.getMonth() - 3); // 加2年 date.setFullYear(date.getFullYear() + 2);
2. 計算日期差
function dateDiffInDays(date1, date2) { const diffTime = Math.abs(date2 - date1); return Math.floor(diffTime / (1000 * 60 * 60 * 24)); } const start = new Date(2023, 0, 1); // 2023年1月1日 const end = new Date(2023, 9, 20); // 2023年10月20日 console.log(dateDiffInDays(start, end)); // 292天
七、最佳實踐與注意事項
月份從0開始:一月是0,十二月是11
使用getFullYear():不要使用已廢棄的getYear()
處理時區(qū)問題:明確業(yè)務是否需要考慮時區(qū)
日期不可變性:進行日期計算時最好創(chuàng)建新對象
// 推薦做法 const newDate = new Date(oldDate.getTime()); newDate.setDate(newDate.getDate() + 1); // 不推薦 - 修改了原對象 oldDate.setDate(oldDate.getDate() + 1);
性能考慮:頻繁創(chuàng)建Date對象會影響性能
使用庫處理復雜邏輯:考慮使用moment.js、date-fns等庫處理復雜日期操作
八、現(xiàn)代JavaScript日期處理
1. Temporal提案(未來標準)
// 提案階段,未來可能的標準API const today = Temporal.Now.plainDateISO(); console.log(today.year); // 2023 console.log(today.month); // 10 (不再是0-based) console.log(today.day); // 20
2. 使用第三方庫
// 使用date-fns庫示例 import { format, addDays, differenceInDays } from 'date-fns'; const today = new Date(); console.log(format(today, 'yyyy-MM-dd')); // "2023-10-20" const tomorrow = addDays(today, 1); console.log(differenceInDays(tomorrow, today)); // 1
總結(jié)
JavaScript的Date對象提供了豐富的API來處理日期和時間:
獲取當前日期時間:
new Date()
獲取年份:
getFullYear()
(推薦)獲取日期組件:
getDate()
,getMonth()
,getHours()
等格式化顯示:
toLocaleString()
,toISOString()
等方法日期計算:通過
setDate()
,setFullYear()
等方法進行
記住處理日期時的常見陷阱(如月份從0開始),對于復雜場景可以考慮使用專門的日期庫。隨著Temporal提案的推進,未來JavaScript的日期處理將變得更加簡單和強大。
相關文章
javascrit中undefined和null的區(qū)別詳解
這篇文章主要介紹了javascrit中undefined和null的區(qū)別詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04純javascript實現(xiàn)選擇框的全選與反選功能
這篇文章主要介紹了純javascript實現(xiàn)選擇框的全選與反選 ,需要的朋友可以參考下2019-04-04JavaScript實現(xiàn)經(jīng)緯度轉(zhuǎn)換常用方法總結(jié)
WGS84坐標系、GCJ02坐標系、BD09坐標系和Web 墨卡托投影坐標系是我們常見的四個坐標系。這篇文章為大家整理了這四個坐標系之間相互轉(zhuǎn)換的方法,需要的可以參考一下2023-02-02