JavaScript日期和時間的格式化及其它常用處理方法
一、日期和時間的格式化
1、原生方法
【1】使用toLocaleString 方法
//Date 對象有一個 toLocaleString 方法,該方法可以根據(jù)本地時間和地區(qū)設(shè)置格式化日期時間。例如:
//toLocaleString 方法接受兩個參數(shù),第一個參數(shù)是地區(qū)設(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 對象
//Intl.DateTimeFormat 對象能使日期和時間在特定的語言環(huán)境下格式化??梢允褂迷搶ο髞砩梢粋€格式化日期時間的實例,并根據(jù)需要來設(shè)置日期時間的格式和時區(qū)。例如:
//可以在選項中指定需要的日期時間格式,包括年、月、日、時、分、秒等。同時也可以設(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、使用字符串操作方法
//可以使用字符串操作方法來將日期時間格式化為特定格式的字符串。例如:
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
//以上代碼使用了字符串模板和字符串操作方法,將日期時間格式化為 YYYY-MM-DD HH:mm:ss 的格式??梢愿鶕?jù)實際需要來修改格式。3、自定義格式化函數(shù)
【1】不可指定格式的格式化函數(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
//以上代碼定義了一個 formatDateTime 函數(shù)和一個 pad 函數(shù),用于格式化日期時間并補齊數(shù)字??梢愿鶕?jù)需要修改格式,因此通用性較低。【2】可指定格式的格式化函數(shù)
//下面是一個通用較高的自定義日期時間格式化函數(shù)的示例:
function formatDateTime(date, format) {
const o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小時
'H+': date.getHours(), // 小時
'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;
}
//這個函數(shù)接受兩個參數(shù),第一個參數(shù)是要格式化的日期時間,可以是 Date 對象或表示日期時間的字符串,第二個參數(shù)是要格式化的格式,例如 yyyy-MM-dd HH:mm:ss。該函數(shù)會將日期時間格式化為指定的格式,并返回格式化后的字符串。
//該函數(shù)使用了正則表達式來匹配格式字符串中的占位符,然后根據(jù)對應(yīng)的日期時間值來替換占位符。其中,y 會被替換為年份,M、d、h、H、m、s、q、S、a、A 分別表示月份、日期、小時(12 小時制)、小時(24 小時制)、分鐘、秒、季度、毫秒、上午/下午、AM/PM。
//使用該函數(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ù)實際需要修改格式化的格式,以及支持更多的占位符和格式化選項。4、使用第三方庫
//除了原生的方法外,還有很多第三方庫可以用來格式化日期時間,例如 Moment.js 和 date-fns 等。這些庫提供了更多的日期時間格式化選項,并且可以兼容不同的瀏覽器和環(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ù)實際需要進行格式化。二、日期和時間的其它常用處理方法
1、創(chuàng)建 Date 對象
要創(chuàng)建一個 Date 對象,可以使用 new Date(),不傳入任何參數(shù)則會使用當(dāng)前時間。也可以傳入一個日期字符串或毫秒數(shù),例如:
const now = new Date(); // 當(dāng)前時間
const date1 = new Date("2022-01-01"); // 指定日期字符串
const date2 = new Date(1640995200000); // 指定毫秒數(shù)2、日期和時間的獲取
Date 對象可以通過許多方法獲取日期和時間的各個部分,例如:
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(); // 小時,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、日期和時間的計算
?可以使用 Date 對象的 set 方法來設(shè)置日期和時間的各個部分,也可以使用 get 方法獲取日期和時間的各個部分,然后進行計算。例如,要計算兩個日期之間的天數(shù),可以先將兩個日期轉(zhuǎn)換成毫秒數(shù),然后計算它們之間的差值,最后將差值轉(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、日期和時間的比較
可以使用 Date 對象的 getTime() 方法將日期轉(zhuǎn)換成毫秒數(shù),然后比較兩個日期的毫秒數(shù)大小,以確定它們的順序。例如,要比較兩個日期的先后順序,可以將它們轉(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、日期和時間的操作
可以使用 Date 對象的一些方法來進行日期和時間的操作,例如,使用 setDate() 方法設(shè)置日期,使用 setHours() 方法設(shè)置小時數(shù),使用 setTime() 方法設(shè)置毫秒數(shù)等等。例如,要將日期增加一天,可以使用 setDate() 方法,例如:
const date = new Date(); date.setDate(date.getDate() + 1); // 增加一天 console.log(date.toLocaleDateString()); // 輸出增加一天后的日期
6、獲取上周、本周、上月、本月和本年的開始時間和結(jié)束時間
// 獲取本周的開始時間和結(jié)束時間
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 };
}
//獲取時間區(qū)間的示例:
//const thisWeek = getThisWeek();
//console.log(thisWeek.start); // 本周的開始時間
//console.log(thisWeek.end); // 本周的結(jié)束時間
// 獲取上周的開始時間和結(jié)束時間
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 };
}
// 獲取本月的開始時間和結(jié)束時間
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 };
}
// 獲取上月的開始時間和結(jié)束時間
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 };
}
// 獲取本年的開始時間和結(jié)束時間
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ù)出生日期計算年齡
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;
}
//使用這個函數(shù)計算年齡的示例:
//const birthDate = new Date("1990-01-01");
//const age = calculateAge(birthDate);
//console.log(age); // 338、其他相關(guān)的知識點
在使用 Date 對象時,需要注意以下幾點:
(1)月份從 0 開始,0 表示一月,11 表示十二月;
(2)getDate() 方法返回的是日期,而 getDay() 方法返回的是星期幾;
(3)Date 對象的年份是完整的四位數(shù),例如 2023;
(4)使用 new Date() 創(chuàng)建 Date 對象時,返回的是當(dāng)前時區(qū)的時間,如果需要使用 UTC 時間,可以使用 new Date(Date.UTC())
總結(jié)
到此這篇關(guān)于JavaScript日期和時間的格式化及其它常用處理方法的文章就介紹到這了,更多相關(guān)JS日期和時間格式化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
typescript 中 for..of 和 for..in的區(qū)別
本文主要介紹了typescript 中 for..of 和 for..in的區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-10-10
基于JavaScript將表單序列化類型的數(shù)據(jù)轉(zhuǎn)化成對象的處理(允許對象中包含對象)
這篇文章主要介紹了基于JavaScript將表單序列化類型的數(shù)據(jù)轉(zhuǎn)化成對象的處理(允許對象中包含對象) 的相關(guān)資料,需要的朋友可以參考下2015-12-12
在layui中l(wèi)ayer彈出層點擊事件無效的解決方法
今天小編就為大家分享一篇在layui中l(wèi)ayer彈出層點擊事件無效的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09
echarts拖拽滑塊dataZoom-slider自定義樣式簡單適配移動端
在電腦端和移動端的數(shù)據(jù)展示中,針對移動端的特殊性,進行了一系列優(yōu)化措施,這篇文章主要介紹了echarts拖拽滑塊dataZoom-slider自定義樣式簡單適配移動端的相關(guān)資料,需要的朋友可以參考下2024-09-09
Ajax+FormData+javascript實現(xiàn)無刷新表單信息提交
在前端開發(fā)中ajax,formdata和js實現(xiàn)無刷新表單信息提交非常棒,接下來通過本文給大家介紹Ajax+FormData+javascript實現(xiàn)無刷新表單信息提交的相關(guān)資料,需要的朋友可以參考下2016-10-10
模仿JQuery.extend函數(shù)擴展自己對象的js代碼
最近打算寫個自己的js工具集合,把自己平常經(jīng)常使用的方法很好的封裝起來,其中模仿了jq的結(jié)構(gòu)。2009-12-12
基于JS實現(xiàn)移動端訪問PC端頁面時跳轉(zhuǎn)到對應(yīng)的移動端網(wǎng)頁
不想通過CSS自適應(yīng)在PC端和移動端分別顯示不同的樣式,那么只能通過在移動端訪問PC端網(wǎng)頁時跳轉(zhuǎn)到對應(yīng)的移動端網(wǎng)頁了,那么怎么跳轉(zhuǎn)呢,網(wǎng)上也有很多文章說明,以下實現(xiàn)思路經(jīng)過小編測試過,需要的朋友可以參考下2016-04-04

