JavaScript?Date對(duì)象之獲取日期、時(shí)間與年份完全指南
一、Date 對(duì)象基礎(chǔ)
JavaScript 的 Date 對(duì)象是處理日期和時(shí)間的內(nèi)置對(duì)象,它可以表示從 1970 年 1 月 1 日 UTC(協(xié)調(diào)世界時(shí))至今的毫秒數(shù)。
創(chuàng)建 Date 實(shí)例
// 1. 獲取當(dāng)前日期和時(shí)間
const now = new Date();
// 2. 通過時(shí)間戳創(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開始計(jì)數(shù)的(0=一月,11=十二月)
const specificDate = new Date(2023, 9, 20, 14, 30, 0);二、獲取當(dāng)前日期和時(shí)間
1. 獲取完整日期時(shí)間字符串
const now = new Date(); // 1. 本地日期時(shí)間字符串 console.log(now.toString()); // 示例輸出: "Fri Oct 20 2023 14:30:45 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)" // 2. ISO 格式字符串 console.log(now.toISOString()); // 示例輸出: "2023-10-20T06:30:45.000Z" // 3. 本地日期字符串 console.log(now.toDateString()); // 示例輸出: "Fri Oct 20 2023" // 4. 本地時(shí)間字符串 console.log(now.toTimeString()); // 示例輸出: "14:30:45 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)" // 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. 獲取各個(gè)日期時(shí)間組件
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 (表示星期五) // 獲取小時(shí)(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 // 獲取時(shí)間戳(自1970年1月1日以來的毫秒數(shù)) const timestamp = now.getTime(); // 1697783445000
三、獲取當(dāng)前年份的多種方式
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)四、日期格式化實(shí)用技巧
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. 相對(duì)時(shí)間顯示
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)}小時(shí)前`;
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小時(shí)前"
console.log(timeAgo(new Date(2023, 9, 1))); // "2023-10-01"五、時(shí)區(qū)處理
1. 獲取UTC時(shí)間
const now = new Date(); // 獲取UTC時(shí)間組件 const utcHours = now.getUTCHours(); const utcMinutes = now.getUTCMinutes(); // 轉(zhuǎn)換為UTC字符串 console.log(now.toUTCString()); // "Fri, 20 Oct 2023 06:30:45 GMT"
2. 時(shí)區(qū)轉(zhuǎn)換
function convertTimezone(date, timezone) {
return new Date(date.toLocaleString('en-US', { timeZone: timezone }));
}
// 將當(dāng)前時(shí)間轉(zhuǎn)換為紐約時(shí)間
const nyTime = convertTimezone(new Date(), 'America/New_York');
console.log(nyTime.toLocaleString());
// "10/20/2023, 2:30:45 AM" (假設(shè)北京時(shí)間是14:30)六、日期計(jì)算
1. 日期加減
// 加5天 const date = new Date(); date.setDate(date.getDate() + 5); // 減3個(gè)月 date.setMonth(date.getMonth() - 3); // 加2年 date.setFullYear(date.getFullYear() + 2);
2. 計(jì)算日期差
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天七、最佳實(shí)踐與注意事項(xiàng)
月份從0開始:一月是0,十二月是11
使用getFullYear():不要使用已廢棄的getYear()
處理時(shí)區(qū)問題:明確業(yè)務(wù)是否需要考慮時(shí)區(qū)
日期不可變性:進(jìn)行日期計(jì)算時(shí)最好創(chuàng)建新對(duì)象
// 推薦做法 const newDate = new Date(oldDate.getTime()); newDate.setDate(newDate.getDate() + 1); // 不推薦 - 修改了原對(duì)象 oldDate.setDate(oldDate.getDate() + 1);
性能考慮:頻繁創(chuàng)建Date對(duì)象會(huì)影響性能
使用庫處理復(fù)雜邏輯:考慮使用moment.js、date-fns等庫處理復(fù)雜日期操作
八、現(xiàn)代JavaScript日期處理
1. Temporal提案(未來標(biāo)準(zhǔn))
// 提案階段,未來可能的標(biāo)準(zhǔn)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對(duì)象提供了豐富的API來處理日期和時(shí)間:
獲取當(dāng)前日期時(shí)間:
new Date()獲取年份:
getFullYear()(推薦)獲取日期組件:
getDate(),getMonth(),getHours()等格式化顯示:
toLocaleString(),toISOString()等方法日期計(jì)算:通過
setDate(),setFullYear()等方法進(jìn)行
記住處理日期時(shí)的常見陷阱(如月份從0開始),對(duì)于復(fù)雜場(chǎng)景可以考慮使用專門的日期庫。隨著Temporal提案的推進(jìn),未來JavaScript的日期處理將變得更加簡(jiǎn)單和強(qiáng)大。
相關(guān)文章
用JavaScript實(shí)現(xiàn)UrlEncode和UrlDecode的腳本代碼
用js自定義函數(shù)寫的實(shí)現(xiàn)url加密解密的實(shí)現(xiàn)代碼,需要的朋友可以參考下2008-07-07
JavaScript中實(shí)現(xiàn)數(shù)組分組功能的方法詳解
最近,JavaScript引入了一個(gè)備受期待的功能:原生支持?jǐn)?shù)組分組,這一特性使得在處理復(fù)雜的數(shù)據(jù)集時(shí)變得更加簡(jiǎn)單和高效,本文將深入探討這一全新的JavaScript特性,希望對(duì)大家有所幫助2023-12-12
javascript 判斷當(dāng)前瀏覽器版本并判斷ie版本
這篇文章主要介紹了javascript 判斷當(dāng)前瀏覽器版本并判斷ie版本的相關(guān)資料,需要的朋友可以參考下2017-02-02
超鏈接怎么正確調(diào)用javascript函數(shù)
本文介紹使用超鏈接調(diào)用javasript函數(shù)且不會(huì)影響GIF圖片動(dòng)畫的方法,有遇到相同問題的小伙伴可以參考一下。2016-05-05
JavaScript緩沖運(yùn)動(dòng)實(shí)現(xiàn)方法(2則示例)
這篇文章主要介紹了JavaScript緩沖運(yùn)動(dòng)實(shí)現(xiàn)方法,簡(jiǎn)單分析了JavaScript緩沖運(yùn)動(dòng)的實(shí)現(xiàn)原理與相關(guān)運(yùn)算技巧,并給出了兩則實(shí)例代碼予以總結(jié)分析,需要的朋友可以參考下2016-01-01
移動(dòng)端利用H5實(shí)現(xiàn)壓縮圖片上傳功能
這篇文章主要為大家詳細(xì)介紹了移動(dòng)端利用H5實(shí)現(xiàn)壓縮圖片上傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03
JavaScript中剩余參數(shù)語法(Rest Parameters)的使用
本文主要介紹了JavaScript中剩余參數(shù)語法(Rest Parameters)的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-06-06
JS實(shí)現(xiàn)簡(jiǎn)單打字測(cè)試
這篇文章主要為大家詳細(xì)介紹了JS實(shí)現(xiàn)簡(jiǎn)單打字測(cè)試,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-06-06

