JavaScript日期和時(shí)間的格式化及其它常用處理方法
一、日期和時(shí)間的格式化
1、原生方法
【1】使用toLocaleString
方法
//Date 對(duì)象有一個(gè) toLocaleString 方法,該方法可以根據(jù)本地時(shí)間和地區(qū)設(shè)置格式化日期時(shí)間。例如: //toLocaleString 方法接受兩個(gè)參數(shù),第一個(gè)參數(shù)是地區(qū)設(shè)置,第二個(gè)參數(shù)是選項(xiàng),用于指定日期時(shí)間格式和時(shí)區(qū)信息。 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
【2】使用 Intl.DateTimeFormat
對(duì)象
//Intl.DateTimeFormat 對(duì)象能使日期和時(shí)間在特定的語(yǔ)言環(huán)境下格式化??梢允褂迷搶?duì)象來(lái)生成一個(gè)格式化日期時(shí)間的實(shí)例,并根據(jù)需要來(lái)設(shè)置日期時(shí)間的格式和時(shí)區(qū)。例如: //可以在選項(xiàng)中指定需要的日期時(shí)間格式,包括年、月、日、時(shí)、分、秒等。同時(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/19/2023, 9:17:40 AM const dateCN = new Date(); const formatterCN = new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', }); console.log(formatterCN.format(dateCN)); // 2023/02/19 22:17:40
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ù)
【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ù)需要修改格式,因此通用性較低。
【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í)間
// 獲取本周的開(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 }; } //獲取時(shí)間區(qū)間的示例: //const thisWeek = getThisWeek(); //console.log(thisWeek.start); // 本周的開(kāi)始時(shí)間 //console.log(thisWeek.end); // 本周的結(jié)束時(shí)間 // 獲取上周的開(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 }; } // 獲取本年的開(kāi)始時(shí)間和結(jié)束時(shí)間 function getThisYear() { const now = new Date(); const yearStart = new Date(now.getFullYear(), 0, 1); const yearEnd = new Date(now.getFullYear(), 11, 31); return { start: yearStart, end: yearEnd }; }
7、根據(jù)出生日期計(jì)算年齡
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ù)計(jì)算年齡的示例: //const birthDate = new Date("1990-01-01"); //const age = calculateAge(birthDate); //console.log(age); // 33
8、其他相關(guān)的知識(shí)點(diǎn)
在使用 Date 對(duì)象時(shí),需要注意以下幾點(diǎn):
(1)月份從 0 開(kāi)始,0 表示一月,11 表示十二月;
(2)getDate() 方法返回的是日期,而 getDay() 方法返回的是星期幾;
(3)Date 對(duì)象的年份是完整的四位數(shù),例如 2023;
(4)使用 new Date() 創(chuàng)建 Date 對(duì)象時(shí),返回的是當(dāng)前時(shí)區(qū)的時(shí)間,如果需要使用 UTC 時(shí)間,可以使用 new Date(Date.UTC())
總結(jié)
到此這篇關(guān)于JavaScript日期和時(shí)間的格式化及其它常用處理方法的文章就介紹到這了,更多相關(guān)JS日期和時(shí)間格式化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript createElement()創(chuàng)建input不能設(shè)置name屬性的解決方法
今天在使用document.createElement()動(dòng)態(tài)創(chuàng)建input時(shí),發(fā)現(xiàn)不能為其name賦值,以下是測(cè)試代碼。2009-10-10前端實(shí)現(xiàn)docx文件預(yù)覽的3種方式舉例及分析
這篇文章主要介紹了前端實(shí)現(xiàn)docx文件預(yù)覽的3種方式,三種方式分別是docx-preview、vue-office和mammoth,文中給出了詳細(xì)的代碼示例,需要的朋友可以參考下2025-03-03javascript顯示選擇目錄對(duì)話(huà)框的代碼
js 目錄對(duì)話(huà)框顯示代碼2008-11-11uniapp實(shí)現(xiàn)tabBar-switchTab之間的傳參方法
這篇文章主要介紹了uniapp實(shí)現(xiàn)tabBar-switchTab之間的傳參方式,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-01-01JS實(shí)現(xiàn)的簡(jiǎn)單折疊展開(kāi)動(dòng)畫(huà)效果示例
這篇文章主要介紹了JS實(shí)現(xiàn)的簡(jiǎn)單折疊展開(kāi)動(dòng)畫(huà)效果,可實(shí)現(xiàn)類(lèi)似百度頁(yè)面分享按鈕一樣的折疊展開(kāi)動(dòng)畫(huà)效果,涉及javascript頁(yè)面元素屬性動(dòng)態(tài)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-04-04bootstrap fileinput實(shí)現(xiàn)文件上傳功能
這篇文章主要為大家詳細(xì)介紹了bootstrap fileinput實(shí)現(xiàn)文件上傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08JS導(dǎo)出PDF插件的方法(支持中文、圖片使用路徑)
下面小編就為大家?guī)?lái)一篇JS導(dǎo)出PDF插件的方法(支持中文、圖片使用路徑)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-07-07js實(shí)現(xiàn)單一html頁(yè)面兩套css切換代碼
研究了一下JS的用setAttribute方法實(shí)現(xiàn)一個(gè)頁(yè)面兩份樣式表的效果與大家分享下,感興趣的朋友可以參考下哈,希望可以幫助到你2013-04-04ES6 Array常用擴(kuò)展的應(yīng)用實(shí)例分析
這篇文章主要介紹了ES6 Array常用擴(kuò)展的應(yīng)用,結(jié)合實(shí)例形式分析各種常見(jiàn)擴(kuò)展方法針對(duì)Array數(shù)組的轉(zhuǎn)換、遍歷、查找、運(yùn)算等相關(guān)操作技巧,需要的朋友可以參考下2019-06-06