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í)間在特定的語言環(huán)境下格式化??梢允褂迷搶?duì)象來生成一個(gè)格式化日期時(shí)間的實(shí)例,并根據(jù)需要來設(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:402、使用字符串操作方法
//可以使用字符串操作方法來將日期時(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í)際需要來修改格式。3、自定義格式化函數(shù)
【1】不可指定格式的格式化函數(shù)
//可以編寫自定義函數(shù)來格式化日期時(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á)式來匹配格式字符串中的占位符,然后根據(jù)對(duì)應(yīng)的日期時(shí)間值來替換占位符。其中,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ù)可以用來格式化日期時(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ì)象可以通過許多方法獲取日期和時(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 方法來設(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ì)象的一些方法來進(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、獲取上周、本周、上月、本月和本年的開始時(shí)間和結(jié)束時(shí)間
// 獲取本周的開始時(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); // 本周的開始時(shí)間
//console.log(thisWeek.end); // 本周的結(jié)束時(shí)間
// 獲取上周的開始時(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 };
}
// 獲取本月的開始時(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 };
}
// 獲取上月的開始時(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 };
}
// 獲取本年的開始時(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); // 338、其他相關(guān)的知識(shí)點(diǎn)
在使用 Date 對(duì)象時(shí),需要注意以下幾點(diǎn):
(1)月份從 0 開始,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)文章
typescript 中 for..of 和 for..in的區(qū)別
本文主要介紹了typescript 中 for..of 和 for..in的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-10-10
基于JavaScript將表單序列化類型的數(shù)據(jù)轉(zhuǎn)化成對(duì)象的處理(允許對(duì)象中包含對(duì)象)
這篇文章主要介紹了基于JavaScript將表單序列化類型的數(shù)據(jù)轉(zhuǎn)化成對(duì)象的處理(允許對(duì)象中包含對(duì)象) 的相關(guān)資料,需要的朋友可以參考下2015-12-12
在layui中l(wèi)ayer彈出層點(diǎn)擊事件無效的解決方法
今天小編就為大家分享一篇在layui中l(wèi)ayer彈出層點(diǎn)擊事件無效的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-09-09
echarts拖拽滑塊dataZoom-slider自定義樣式簡(jiǎn)單適配移動(dòng)端
在電腦端和移動(dòng)端的數(shù)據(jù)展示中,針對(duì)移動(dòng)端的特殊性,進(jìn)行了一系列優(yōu)化措施,這篇文章主要介紹了echarts拖拽滑塊dataZoom-slider自定義樣式簡(jiǎn)單適配移動(dòng)端的相關(guān)資料,需要的朋友可以參考下2024-09-09
微信小程序?qū)崿F(xiàn)滾動(dòng)Tab選項(xiàng)卡
這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)滾動(dòng)Tab選項(xiàng)卡,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11
Ajax+FormData+javascript實(shí)現(xiàn)無刷新表單信息提交
在前端開發(fā)中ajax,formdata和js實(shí)現(xiàn)無刷新表單信息提交非常棒,接下來通過本文給大家介紹Ajax+FormData+javascript實(shí)現(xiàn)無刷新表單信息提交的相關(guān)資料,需要的朋友可以參考下2016-10-10
模仿JQuery.extend函數(shù)擴(kuò)展自己對(duì)象的js代碼
最近打算寫個(gè)自己的js工具集合,把自己平常經(jīng)常使用的方法很好的封裝起來,其中模仿了jq的結(jié)構(gòu)。2009-12-12
基于JS實(shí)現(xiàn)移動(dòng)端訪問PC端頁(yè)面時(shí)跳轉(zhuǎn)到對(duì)應(yīng)的移動(dòng)端網(wǎng)頁(yè)
不想通過CSS自適應(yīng)在PC端和移動(dòng)端分別顯示不同的樣式,那么只能通過在移動(dòng)端訪問PC端網(wǎng)頁(yè)時(shí)跳轉(zhuǎn)到對(duì)應(yīng)的移動(dòng)端網(wǎng)頁(yè)了,那么怎么跳轉(zhuǎn)呢,網(wǎng)上也有很多文章說明,以下實(shí)現(xiàn)思路經(jīng)過小編測(cè)試過,需要的朋友可以參考下2016-04-04

