JavaScript?日期和時(shí)間的格式化方法
JavaScript 日期和時(shí)間的格式化
一、日期和時(shí)間的格式化
1、原生方法
1.1、使用 toLocaleString 方法
Date 對(duì)象有一個(gè) toLocaleString 方法,該方法可以根據(jù)本地時(shí)間和地區(qū)設(shè)置格式化日期時(shí)間。例如:
const date = new Date(); console.log(date.toLocaleString('en-US', { timeZone: 'America/New_York' })); // 2/16/2023, 8:25:05 AM console.log(date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })); // 2023/2/16 上午8:25:05
toLocaleString 方法接受兩個(gè)參數(shù),第一個(gè)參數(shù)是地區(qū)設(shè)置,第二個(gè)參數(shù)是選項(xiàng),用于指定日期時(shí)間格式和時(shí)區(qū)信息。
1.2、使用 Intl.DateTimeFormat 對(duì)象
Intl.DateTimeFormat 對(duì)象是一個(gè)用于格式化日期和時(shí)間的構(gòu)造函數(shù)??梢允褂迷搶?duì)象來(lái)生成一個(gè)格式化日期時(shí)間的實(shí)例,并根據(jù)需要來(lái)設(shè)置日期時(shí)間的格式和時(shí)區(qū)。例如:
const date = new Date(); const formatter = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', }); console.log(formatter.format(date)); // 2/16/2023, 8:25:05 AM
可以在選項(xiàng)中指定需要的日期時(shí)間格式,包括年、月、日、時(shí)、分、秒等。同時(shí)也可以設(shè)置時(shí)區(qū)信息。
2、使用字符串操作方法
可以使用字符串操作方法來(lái)將日期時(shí)間格式化為特定格式的字符串。例如:
const date = new Date(); const year = date.getFullYear().toString().padStart(4, '0'); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); const hour = date.getHours().toString().padStart(2, '0'); const minute = date.getMinutes().toString().padStart(2, '0'); const second = date.getSeconds().toString().padStart(2, '0'); console.log(`${year}-${month}-${day} ${hour}:${minute}:${second}`); // 2023-02-16 08:25:05
以上代碼使用了字符串模板和字符串操作方法,將日期時(shí)間格式化為 YYYY-MM-DD HH:mm:ss 的格式??梢愿鶕?jù)實(shí)際需要來(lái)修改格式。
3、自定義格式化函數(shù)
3.1、不可指定格式的格式化函數(shù)
可以編寫(xiě)自定義函數(shù)來(lái)格式化日期時(shí)間。例如:
function formatDateTime(date) { const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const hour = date.getHours(); const minute = date.getMinutes(); const second = date.getSeconds(); return `${year}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`; } function pad(num) { return num.toString().padStart(2, '0'); } const date = new Date(); console.log(formatDateTime(date)); // 2023-02-16 08:25:05
以上代碼定義了一個(gè) formatDateTime 函數(shù)和一個(gè) pad 函數(shù),用于格式化日期時(shí)間并補(bǔ)齊數(shù)字。可以根據(jù)需要修改格式,因此通用性較低。
3.2、可指定格式的格式化函數(shù)
下面是一個(gè)通用較高的自定義日期時(shí)間格式化函數(shù)的示例:
function formatDateTime(date, format) { const o = { 'M+': date.getMonth() + 1, // 月份 'd+': date.getDate(), // 日 'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小時(shí) 'H+': date.getHours(), // 小時(shí) 'm+': date.getMinutes(), // 分 's+': date.getSeconds(), // 秒 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度 S: date.getMilliseconds(), // 毫秒 a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午 A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM }; if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); } for (let k in o) { if (new RegExp('(' + k + ')').test(format)) { format = format.replace( RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length) ); } } return format; }
這個(gè)函數(shù)接受兩個(gè)參數(shù),第一個(gè)參數(shù)是要格式化的日期時(shí)間,可以是 Date 對(duì)象或表示日期時(shí)間的字符串,第二個(gè)參數(shù)是要格式化的格式,例如 yyyy-MM-dd HH:mm:ss
。該函數(shù)會(huì)將日期時(shí)間格式化為指定的格式,并返回格式化后的字符串。
該函數(shù)使用了正則表達(dá)式來(lái)匹配格式字符串中的占位符,然后根據(jù)對(duì)應(yīng)的日期時(shí)間值來(lái)替換占位符。其中,y 會(huì)被替換為年份,M、d、h、H、m、s、q、S、a、A 分別表示月份、日期、小時(shí)(12 小時(shí)制)、小時(shí)(24 小時(shí)制)、分鐘、秒、季度、毫秒、上午/下午、AM/PM。
使用該函數(shù)進(jìn)行日期時(shí)間格式化的示例如下:
const date = new Date(); console.log(formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')); // 2023-02-16 08:25:05 console.log(formatDateTime(date, 'yyyy年MM月dd日 HH:mm:ss')); // 2023年02月16日 08:25:05 console.log(formatDateTime(date, 'yyyy-MM-dd HH:mm:ss S')); // 2023-02-16 08:25:05 950 console.log(formatDateTime(date, 'yyyy-MM-dd hh:mm:ss A')); // 2023-02-16 08:25:05 上午
可以根據(jù)實(shí)際需要修改格式化的格式,以及支持更多的占位符和格式化選項(xiàng)。
4、使用第三方庫(kù)
除了原生的方法外,還有很多第三方庫(kù)可以用來(lái)格式化日期時(shí)間,例如 Moment.js 和 date-fns 等。這些庫(kù)提供了更多的日期時(shí)間格式化選項(xiàng),并且可以兼容不同的瀏覽器和環(huán)境。
const date = new Date(); console.log(moment(date).format('YYYY-MM-DD HH:mm:ss')); // 2023-02-16 08:25:05 console.log(dateFns.format(date, 'yyyy-MM-dd HH:mm:ss')); // 2023-02-16 08:25:05
以上是幾種常用的日期時(shí)間格式化方法,在進(jìn)行日期時(shí)間格式化時(shí),可以使用原生的方法、自定義函數(shù)或第三方庫(kù),選擇合適的方法根據(jù)實(shí)際需要進(jìn)行格式化。
二、日期和時(shí)間的其它常用處理方法
1、創(chuàng)建 Date 對(duì)象
要?jiǎng)?chuàng)建一個(gè) Date 對(duì)象,可以使用 new Date(),不傳入任何參數(shù)則會(huì)使用當(dāng)前時(shí)間。也可以傳入一個(gè)日期字符串或毫秒數(shù),例如:
const now = new Date(); // 當(dāng)前時(shí)間 const date1 = new Date("2022-01-01"); // 指定日期字符串 const date2 = new Date(1640995200000); // 指定毫秒數(shù)
2、日期和時(shí)間的獲取
Date 對(duì)象可以通過(guò)許多方法獲取日期和時(shí)間的各個(gè)部分,例如:
const date = new Date(); const year = date.getFullYear(); // 年份,例如 2023 const month = date.getMonth(); // 月份,0-11,0 表示一月,11 表示十二月 const day = date.getDate(); // 日期,1-31 const hour = date.getHours(); // 小時(shí),0-23 const minute = date.getMinutes(); // 分鐘,0-59 const second = date.getSeconds(); // 秒數(shù),0-59 const millisecond = date.getMilliseconds(); // 毫秒數(shù),0-999 const weekday = date.getDay(); // 星期幾,0-6,0 表示周日,6 表示周六
3、日期和時(shí)間的計(jì)算
可以使用 Date 對(duì)象的 set 方法來(lái)設(shè)置日期和時(shí)間的各個(gè)部分,也可以使用 get 方法獲取日期和時(shí)間的各個(gè)部分,然后進(jìn)行計(jì)算。例如,要計(jì)算兩個(gè)日期之間的天數(shù),可以先將兩個(gè)日期轉(zhuǎn)換成毫秒數(shù),然后計(jì)算它們之間的差值,最后將差值轉(zhuǎn)換成天數(shù),例如:
const date1 = new Date("2022-01-01"); const date2 = new Date("2023-02-16"); const diff = date2.getTime() - date1.getTime(); // 毫秒數(shù) const days = diff / (1000 * 60 * 60 * 24); // 天數(shù)
4、日期和時(shí)間的比較
可以使用 Date 對(duì)象的 getTime() 方法將日期轉(zhuǎn)換成毫秒數(shù),然后比較兩個(gè)日期的毫秒數(shù)大小,以確定它們的順序。例如,要比較兩個(gè)日期的先后順序,可以將它們轉(zhuǎn)換成毫秒數(shù),然后比較它們的大小,例如:
const date1 = new Date("2022-01-01"); const date2 = new Date("2023-02-16"); if (date1.getTime() < date2.getTime()) { console.log("date1 在 date2 之前"); } else if (date1.getTime() > date2.getTime()) { console.log("date1 在 date2 之后"); } else { console.log("date1 和 date2 相等"); }
5、日期和時(shí)間的操作
可以使用 Date 對(duì)象的一些方法來(lái)進(jìn)行日期和時(shí)間的操作,例如,使用 setDate() 方法設(shè)置日期,使用 setHours() 方法設(shè)置小時(shí)數(shù),使用 setTime() 方法設(shè)置毫秒數(shù)等等。例如,要將日期增加一天,可以使用 setDate() 方法,例如:
const date = new Date(); date.setDate(date.getDate() + 1); // 增加一天 console.log(date.toLocaleDateString()); // 輸出增加一天后的日期
6、獲取上周、本周、上月和本月的開(kāi)始時(shí)間和結(jié)束時(shí)間
以下是 JavaScript 獲取本周、上周、本月和上月的開(kāi)始時(shí)間和結(jié)束時(shí)間的代碼示例:
// 獲取本周的開(kāi)始時(shí)間和結(jié)束時(shí)間 function getThisWeek() { const now = new Date(); const day = now.getDay() === 0 ? 7 : now.getDay(); // 將周日轉(zhuǎn)換為 7 const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day + 1); const weekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (6 - day) + 1); return { start: weekStart, end: weekEnd }; } // 獲取上周的開(kāi)始時(shí)間和結(jié)束時(shí)間 function getLastWeek() { const now = new Date(); const day = now.getDay() === 0 ? 7 : now.getDay(); // 將周日轉(zhuǎn)換為 7 const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day - 6); const weekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day); return { start: weekStart, end: weekEnd }; } // 獲取本月的開(kāi)始時(shí)間和結(jié)束時(shí)間 function getThisMonth() { const now = new Date(); const monthStart = new Date(now.getFullYear(), now.getMonth(), 1); const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0); return { start: monthStart, end: monthEnd }; } // 獲取上月的開(kāi)始時(shí)間和結(jié)束時(shí)間 function getLastMonth() { const now = new Date(); const monthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1); const monthEnd = new Date(now.getFullYear(), now.getMonth(), 0); return { start: monthStart, end: monthEnd }; }
上述代碼中,getThisWeek()、getLastWeek()、getThisMonth() 和 getLastMonth() 函數(shù)分別返回當(dāng)前時(shí)間所在的本周、上周、本月和上月的開(kāi)始時(shí)間和結(jié)束時(shí)間。這些函數(shù)使用了 Date 對(duì)象的方法,例如 getFullYear()、getMonth() 和 getDate() 等。它們可以用于獲取需要進(jìn)行時(shí)間區(qū)間計(jì)算的場(chǎng)景,例如統(tǒng)計(jì)某個(gè)時(shí)間范圍內(nèi)的數(shù)據(jù)等。
使用這些函數(shù)獲取時(shí)間區(qū)間的示例:
const thisWeek = getThisWeek(); console.log(thisWeek.start); // 本周的開(kāi)始時(shí)間 console.log(thisWeek.end); // 本周的結(jié)束時(shí)間 const lastWeek = getLastWeek(); console.log(lastWeek.start); // 上周的開(kāi)始時(shí)間 console.log(lastWeek.end); // 上周的結(jié)束時(shí)間 const thisMonth = getThisMonth(); console.log(thisMonth.start); // 本月的開(kāi)始時(shí)間 console.log(thisMonth.end); // 本月的結(jié)束時(shí)間 const lastMonth = getLastMonth(); console.log(lastMonth.start); // 上月的開(kāi)始時(shí)間 console.log(lastMonth.end); // 上月的結(jié)束時(shí)間
使用這些函數(shù)可以方便地獲取需要的時(shí)間區(qū)間,并進(jìn)行后續(xù)的操作。
7、根據(jù)出生日期計(jì)算年齡
以下是一個(gè)根據(jù)出生日期計(jì)算年齡的代碼示例,包括了對(duì)閏年的處理:
function calculateAge(birthDate) { const birthYear = birthDate.getFullYear(); const birthMonth = birthDate.getMonth(); const birthDay = birthDate.getDate(); const now = new Date(); let age = now.getFullYear() - birthYear; if (now.getMonth() < birthMonth || (now.getMonth() === birthMonth && now.getDate() < birthDay)) { age--; } // 檢查閏年 const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; const isBirthLeapYear = isLeapYear(birthYear); // 調(diào)整閏年的年齡 if (isBirthLeapYear && birthMonth > 1) { age--; } if (isLeapYear(now.getFullYear()) && now.getMonth() < 1) { age--; } return age; }
這個(gè)函數(shù)接收一個(gè) Date 對(duì)象作為參數(shù),代表出生日期。該函數(shù)計(jì)算當(dāng)前日期與出生日期之間的時(shí)間差,以確定年齡。其中,使用 Date 對(duì)象的 getFullYear()、getMonth() 和 getDate() 方法獲取出生日期的年、月和日。使用當(dāng)前日期的年、月和日計(jì)算出年齡。如果當(dāng)前月份小于出生月份,或當(dāng)前月份等于出生月份但當(dāng)前日期小于出生日期,則年齡減一。在這個(gè)函數(shù)中,定義了一個(gè) isLeapYear() 函數(shù),用于檢查給定的年份是否為閏年。然后,在計(jì)算年齡時(shí),調(diào)用這個(gè)函數(shù),檢查出生年份和當(dāng)前年份是否為閏年。如果出生年份為閏年且出生月份在二月或之后,則年齡減一。如果當(dāng)前年份為閏年且當(dāng)前月份在一月或之前,則年齡減一。這樣,就可以正確計(jì)算含有閏年的出生日期的年齡了。
這種計(jì)算年齡的方法僅是基于當(dāng)前日期和出生日期之間的時(shí)間差,而不是考慮具體的月份和日期。因此,對(duì)于生日還未到的人,計(jì)算的年齡會(huì)比實(shí)際年齡小一歲。
使用這個(gè)函數(shù)計(jì)算年齡的示例:
const birthDate = new Date("1990-01-01"); const age = calculateAge(birthDate); console.log(age); // 33
上述代碼中,構(gòu)造了一個(gè) Date 對(duì)象,它代表出生日期。然后調(diào)用 calculateAge() 函數(shù),將出生日期作為參數(shù)傳入。該函數(shù)返回當(dāng)前日期與出生日期之間的時(shí)間差,以確定年齡。最后打印計(jì)算出的年齡。
8、其他相關(guān)的知識(shí)點(diǎn)
在使用 Date 對(duì)象時(shí),需要注意以下幾點(diǎn):
- 月份從 0 開(kāi)始,0 表示一月,11 表示十二月;
- getDate() 方法返回的是日期,而 getDay() 方法返回的是星期幾;
- Date 對(duì)象的年份是完整的四位數(shù),例如 2023;
- 使用 new Date() 創(chuàng)建 Date 對(duì)象時(shí),返回的是當(dāng)前時(shí)區(qū)的時(shí)間,如果需要使用 UTC 時(shí)間,可以使用 new Date(Date.UTC())。
JavaScript 中的 Date 對(duì)象提供了許多方法和屬性,可以用于處理日期和時(shí)間,根據(jù)具體情況選擇適合的方法和技巧。
到此這篇關(guān)于JavaScript 日期和時(shí)間的格式化的文章就介紹到這了,更多相關(guān)js時(shí)間格式化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- JavaScript實(shí)現(xiàn)Date()日期格式化的3種常用方法
- 微信小程序js時(shí)間戳與日期格式的轉(zhuǎn)換方法
- JavaScript實(shí)現(xiàn)日期格式化的方法匯總
- Vue中金額、日期格式化插件@formatjs/intl的使用及說(shuō)明
- JS獲取當(dāng)前時(shí)間戳與時(shí)間戳轉(zhuǎn)日期時(shí)間格式問(wèn)題
- js日期格式化yyyy-MM-dd問(wèn)題
- java日期時(shí)間格式化@JsonFormat與@DateTimeFormat的使用
- JS日期轉(zhuǎn)化指定格式及獲取月/周日期區(qū)間的方法
相關(guān)文章
JavaScript中定時(shí)器setTimeout()和setInterval()的用法
本文詳細(xì)講解了JavaScript中定時(shí)器setTimeout()和setInterval()的用法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06JavaScript 函數(shù)節(jié)流詳解及方法總結(jié)
這篇文章主要介紹了JavaScript 函數(shù)節(jié)流詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-02-02JS window.opener返回父頁(yè)面的應(yīng)用
網(wǎng)上支付開(kāi)發(fā)分為支付平臺(tái)和客戶端兩部分。當(dāng)客戶端進(jìn)入支付平臺(tái)時(shí),需要在新窗體打開(kāi)支付平臺(tái)頁(yè)面。2009-10-10JS實(shí)現(xiàn)方向鍵切換輸入框焦點(diǎn)的方法
這篇文章主要介紹了JS實(shí)現(xiàn)方向鍵切換輸入框焦點(diǎn)的方法,涉及javascript鼠標(biāo)事件及頁(yè)面元素焦點(diǎn)的切換實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08如何使用不同的方法在 JavaScript 中添加兩個(gè)向量
這篇文章主要介紹了如何在 JavaScript 中添加向量(Vector)類,使用不同的方法在 JavaScript 中添加兩個(gè)向量,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06JavaScript iframe數(shù)據(jù)共享接口實(shí)現(xiàn)方法
在iframe與父窗口或者與子窗口傳遞數(shù)據(jù)是一個(gè)麻煩的事情,如果我們能夠?qū)懸粋€(gè)一勞永逸的接口那就再方便不過(guò)了,下面就來(lái)簡(jiǎn)答介紹一下如何實(shí)現(xiàn)此功能,對(duì)js iframe相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2016-01-01