JavaScript常用的日期時間函數(shù)封裝及其詳細(xì)說明
JavaScript 日期時間函數(shù)封裝
JavaScript 提供了豐富的日期時間處理函數(shù),但直接使用原生 API 可能不夠便捷。通過封裝常用函數(shù),可以提高代碼復(fù)用性和可讀性。以下是一些常用的日期時間函數(shù)封裝及其詳細(xì)說明。
獲取當(dāng)前時間戳
封裝一個函數(shù)獲取當(dāng)前時間戳,可以是毫秒級或秒級。
function getTimestamp(unit = 'ms') {
const timestamp = Date.now();
return unit === 's' ? Math.floor(timestamp / 1000) : timestamp;
}
unit參數(shù)用于指定返回的時間戳單位,默認(rèn)為毫秒('ms'),傳入's'則返回秒級時間戳。Date.now()返回當(dāng)前時間的毫秒數(shù),Math.floor用于向下取整。
格式化日期
將日期對象格式化為指定的字符串形式,例如 YYYY-MM-DD HH:mm:ss。
function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return format
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
date參數(shù)是一個Date對象。format參數(shù)指定輸出的格式,默認(rèn)是YYYY-MM-DD HH:mm:ss。padStart方法用于補零,確保月份、日期等始終是兩位數(shù)。
解析日期字符串
將日期字符串解析為 Date 對象,支持多種常見格式。
function parseDate(dateString) {
if (!dateString) return new Date();
if (dateString instanceof Date) return dateString;
if (typeof dateString === 'number') return new Date(dateString);
const patterns = [
/^(\d{4})-(\d{2})-(\d{2})$/, // YYYY-MM-DD
/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/, // YYYY-MM-DD HH:mm:ss
/^(\d{4})\/(\d{2})\/(\d{2})$/, // YYYY/MM/DD
];
for (const pattern of patterns) {
const match = dateString.match(pattern);
if (match) {
const [, year, month, day, hours = 0, minutes = 0, seconds = 0] = match;
return new Date(year, month - 1, day, hours, minutes, seconds);
}
}
return new Date(dateString); // Fallback to native parsing
}
dateString可以是Date對象、時間戳或字符串。- 函數(shù)嘗試匹配常見的日期格式,如
YYYY-MM-DD或YYYY-MM-DD HH:mm:ss。 - 如果無法匹配任何模式,則回退到原生
Date解析。
計算日期差
計算兩個日期之間的差值,返回天、小時、分鐘或秒。
function dateDiff(startDate, endDate, unit = 'day') {
const diffMs = endDate - startDate;
const units = {
day: 1000 * 60 * 60 * 24,
hour: 1000 * 60 * 60,
minute: 1000 * 60,
second: 1000,
};
return Math.floor(diffMs / units[unit]);
}
startDate和endDate是Date對象或時間戳。unit參數(shù)指定返回的單位,支持day、hour、minute或second。- 函數(shù)返回兩個日期之間的整數(shù)差值。
日期加減
對日期進行加減操作,支持年、月、日等單位。
function dateAdd(date, amount, unit = 'day') {
const result = new Date(date);
const units = {
year: 'FullYear',
month: 'Month',
day: 'Date',
hour: 'Hours',
minute: 'Minutes',
second: 'Seconds',
};
if (units[unit]) {
result[`set${units[unit]}`](result[`get${units[unit]}`]() + amount);
}
return result;
}
date是Date對象或時間戳。amount是要加減的數(shù)量,可以是正數(shù)或負(fù)數(shù)。unit指定操作的單位,如year、month、day等。- 函數(shù)返回一個新的
Date對象,不會修改原始日期。
獲取月份的天數(shù)
獲取指定年份和月份的天數(shù)。
function getDaysInMonth(year, month) {
return new Date(year, month + 1, 0).getDate();
}
year和month是整數(shù),月份從 0 開始(0 表示一月)。- 函數(shù)返回該月的天數(shù),自動處理閏年。
判斷是否為閏年
判斷指定年份是否為閏年。
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
year是整數(shù)。- 函數(shù)返回布爾值,
true表示是閏年。
獲取季度
根據(jù)月份獲取所在的季度。
function getQuarter(month) {
return Math.floor(month / 3) + 1;
}
month是整數(shù),從 0 開始。- 函數(shù)返回 1 到 4 之間的整數(shù),表示季度。
時間戳轉(zhuǎn)日期
將時間戳轉(zhuǎn)換為 Date 對象。
function timestampToDate(timestamp) {
return new Date(timestamp);
}
timestamp是毫秒級時間戳。- 函數(shù)返回對應(yīng)的
Date對象。
日期轉(zhuǎn)時間戳
將 Date 對象或日期字符串轉(zhuǎn)換為時間戳。
function dateToTimestamp(date, unit = 'ms') {
const timestamp = date instanceof Date ? date.getTime() : new Date(date).getTime();
return unit === 's' ? Math.floor(timestamp / 1000) : timestamp;
}
date可以是Date對象、時間戳或日期字符串。unit指定返回的時間戳單位,默認(rèn)為毫秒('ms'),傳入's'則返回秒級。
判斷日期是否相等
比較兩個日期是否相等,支持精確到天、小時或分鐘。
function isSameDate(date1, date2, unit = 'day') {
const d1 = new Date(date1);
const d2 = new Date(date2);
const units = {
year: 'FullYear',
month: 'Month',
day: 'Date',
hour: 'Hours',
minute: 'Minutes',
};
if (units[unit]) {
return d1[`get${units[unit]}`]() === d2[`get${units[unit]}`]();
}
return d1.getTime() === d2.getTime();
}
date1和date2是Date對象、時間戳或日期字符串。unit指定比較的精度,如year、month、day等。- 函數(shù)返回布爾值,表示兩個日期是否相等。
獲取當(dāng)前時間的零點
獲取當(dāng)前日期的零點時間(00:00:00)。
function getStartOfDay(date) {
const d = new Date(date);
d.setHours(0, 0, 0, 0);
return d;
}
date是Date對象、時間戳或日期字符串。- 函數(shù)返回一個新的
Date對象,時間部分設(shè)置為零點。
獲取當(dāng)前時間的結(jié)束時間
獲取當(dāng)前日期的結(jié)束時間(23:59:59)。
function getEndOfDay(date) {
const d = new Date(date);
d.setHours(23, 59, 59, 999);
return d;
}
date是Date對象、時間戳或日期字符串。- 函數(shù)返回一個新的
Date對象,時間部分設(shè)置為結(jié)束時間。
判斷日期是否在范圍內(nèi)
判斷一個日期是否在指定的日期范圍內(nèi)。
function isDateInRange(date, startDate, endDate) {
const d = new Date(date);
const start = new Date(startDate);
const end = new Date(endDate);
return d >= start && d <= end;
}
date是待檢查的日期。startDate和endDate是范圍的起始和結(jié)束日期。- 函數(shù)返回布爾值,表示日期是否在范圍內(nèi)。
獲取星期幾
獲取指定日期是星期幾,返回數(shù)字或名稱。
function getDayOfWeek(date, format = 'number') {
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const day = new Date(date).getDay();
return format === 'name' ? days[day] : day;
}
date是Date對象、時間戳或日期字符串。format指定返回格式,'number'返回 0-6(0 是周日),'name'返回英文名稱。
獲取時間段的月份列表
獲取兩個日期之間的所有月份。
function getMonthsBetweenDates(startDate, endDate) {
const start = new Date(startDate);
const end = new Date(endDate);
const months = [];
let current = new Date(start);
while (current <= end) {
months.push(new Date(current));
current.setMonth(current.getMonth() + 1);
}
return months;
}
startDate和endDate是Date對象、時間戳或日期字符串。- 函數(shù)返回一個數(shù)組,包含該時間段內(nèi)的所有月份。
時區(qū)轉(zhuǎn)換
將日期從一個時區(qū)轉(zhuǎn)換到另一個時區(qū)。
function convertTimeZone(date, targetTimeZone) {
const options = { timeZone: targetTimeZone };
return new Date(date.toLocaleString('en-US', options));
}
date是Date對象、時間戳或日期字符串。targetTimeZone是目標(biāo)時區(qū),如'America/New_York'。- 函數(shù)返回轉(zhuǎn)換后的
Date對象。
日期有效性檢查
檢查一個日期是否有效。
function isValidDate(date) {
return date instanceof Date && !isNaN(date.getTime());
}
date是待檢查的日期。- 函數(shù)返回布爾值,表示日期是否有效。
總結(jié)
以上封裝涵蓋了 JavaScript 日期時間處理的常見需求,包括格式化、解析、計算、比較和時區(qū)轉(zhuǎn)換等。通過合理封裝,可以減少重復(fù)代碼,提高開發(fā)效率。實際使用時,可以根據(jù)項目需求進一步調(diào)整或擴展這些函數(shù)。
相關(guān)文章
前端獲取資源的方式(ajax、fetch)以及其區(qū)別詳解
Fetch 被稱之為下一代 Ajax 技術(shù),內(nèi)部采用 Promise 方式處理數(shù)據(jù)API 語法簡潔明了,這篇文章主要給大家介紹了關(guān)于前端獲取資源的方式(ajax、fetch)以及其區(qū)別的相關(guān)資料,需要的朋友可以參考下2024-07-07
JS實現(xiàn)十字坐標(biāo)跟隨鼠標(biāo)效果
這篇文章給大家分享一下通過JS實現(xiàn)十字坐標(biāo)跟隨鼠標(biāo)效果的代碼,有需要的朋友參考學(xué)習(xí)下吧。2017-12-12
微信小程序?qū)崿F(xiàn)一張或多張圖片上傳(云開發(fā))
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)一張或多張圖片上傳,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-09-09
JS如何去掉小數(shù)末尾多余的0,并且最多保留兩位小數(shù)
這篇文章主要介紹了JS如何去掉小數(shù)末尾多余的0,并且最多保留兩位小數(shù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
javascript實現(xiàn)多級聯(lián)動下拉菜單的方法
這篇文章主要介紹了javascript實現(xiàn)多級聯(lián)動下拉菜單的方法,通過javascript自定義函數(shù)實現(xiàn)對多級聯(lián)動下拉菜單的操作,是非常實用的技巧,需要的朋友可以參考下2015-02-02

