JavaScript時間格式整理大全(附大量示例)
前言
在 JS 中,處理時間和日期是常見的需求。無論是展示當前時間、格式化日期字符串,還是進行時間計算,JavaScript 都提供了豐富的 API 來滿足這些需求。本文將詳細介紹如何使用 JavaScript 生成各種時間格式,從基礎到高級,涵蓋常見的場景。內容比較多,請大家搭配目錄食用。
基礎時間獲取
1.1 獲取當前時間
JavaScript 提供了 Date
對象來處理日期和時間。要獲取當前時間,只需創(chuàng)建一個 Date
對象即可:
const now = new Date(); console.log(now); // 輸出當前時間的完整日期和時間
1.2 獲取時間戳
時間戳表示從 1970 年 1 月 1 日 00:00:00 UTC 到當前時間的毫秒數??梢允褂?nbsp;getTime()
方法或 Date.now()
來獲取時間戳:
const timestamp1 = new Date().getTime(); const timestamp2 = Date.now(); console.log(timestamp1, timestamp2); // 輸出當前時間的時間戳
時間格式化
2.1 使用 toLocaleString() 格式化時間
toLocaleString()
方法可以根據本地化設置格式化日期和時間:
const now = new Date(); console.log(now.toLocaleString()); // 輸出本地化的日期和時間 console.log(now.toLocaleDateString()); // 輸出本地化的日期 console.log(now.toLocaleTimeString()); // 輸出本地化的時間
2.2 自定義格式化
如果需要更靈活的格式化,可以手動拼接日期和時間的各個部分:
const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份從0開始,需要加1 const day = String(now.getDate()).padStart(2, '0'); const hours = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); const formattedDate = `${year}-${month}-${day}`; const formattedTime = `${hours}:${minutes}:${seconds}`; const formattedDateTime = `${formattedDate} ${formattedTime}`; console.log(formattedDate); // 輸出格式化的日期,如 "2023-10-05" console.log(formattedTime); // 輸出格式化的時間,如 "14:30:45" console.log(formattedDateTime); // 輸出格式化的日期和時間,如 "2023-10-05 14:30:45"
2.3 使用 Intl.DateTimeFormat 進行高級格式化
Intl.DateTimeFormat
對象提供了更強大的本地化日期和時間格式化功能:
const now = new Date(); const formatter = new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false // 使用24小時制 }); console.log(formatter.format(now)); // 輸出格式化的日期和時間,如 "2023/10/05 14:30:45"
時間計算
3.1 時間加減
可以通過修改 Date
對象的各個部分來進行時間加減:
const now = new Date(); now.setHours(now.getHours() + 1); // 當前時間加1小時 now.setDate(now.getDate() + 7); // 當前日期加7天 console.log(now);
3.2 計算時間差
可以通過時間戳來計算兩個時間點之間的差值:
const start = new Date('2023-10-01T00:00:00'); const end = new Date('2023-10-05T12:00:00'); const diffInMilliseconds = end - start; // 時間差,單位為毫秒 const diffInSeconds = diffInMilliseconds / 1000; const diffInMinutes = diffInSeconds / 60; const diffInHours = diffInMinutes / 60; const diffInDays = diffInHours / 24; console.log(diffInDays); // 輸出時間差,如 "4.5" 天
時區(qū)處理
4.1 獲取當前時區(qū)
可以使用 Intl.DateTimeFormat
獲取當前時區(qū):
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; console.log(timeZone); // 輸出當前時區(qū),如 "Asia/Shanghai"
4.2 轉換時區(qū)
可以使用 toLocaleString()
或 Intl.DateTimeFormat
來轉換時區(qū):
const now = new Date(); const options = { timeZone: 'America/New_York', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }; const formatter = new Intl.DateTimeFormat('en-US', options); console.log(formatter.format(now)); // 輸出紐約時間,如 "10/05/2023 02:30:45"
第三方庫推薦
雖然 JavaScript 原生的 Date
對象已經足夠強大,但在處理復雜的日期和時間操作時,使用第三方庫可以更加方便。以下是幾個常用的日期處理庫:
- Moment.js: 功能強大,但體積較大,推薦使用其替代品。
- Day.js: Moment.js 的輕量級替代品,API 兼容,體積小。
- date-fns: 模塊化設計,按需引入,功能豐富。
// 使用 Day.js 格式化時間 const dayjs = require('dayjs'); console.log(dayjs().format('YYYY-MM-DD HH:mm:ss')); // 輸出格式化的日期和時間
常用的格式示例
1. 基礎時間格式
const now = new Date(); // 完整日期和時間 console.log(now.toString()); // "Thu Oct 05 2023 14:30:45 GMT+0800 (China Standard Time)" // ISO 格式 console.log(now.toISOString()); // "2023-10-05T06:30:45.000Z" // 本地日期和時間 console.log(now.toLocaleString()); // "2023/10/5 14:30:45" (根據本地化設置) // 本地日期 console.log(now.toLocaleDateString()); // "2023/10/5" // 本地時間 console.log(now.toLocaleTimeString()); // "14:30:45"
2. 自定義格式化
const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); const day = String(now.getDate()).padStart(2, '0'); const hours = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); // 年-月-日 console.log(`${year}-${month}-${day}`); // "2023-10-05" // 時:分:秒 console.log(`${hours}:${minutes}:${seconds}`); // "14:30:45" // 年/月/日 時:分:秒 console.log(`${year}/${month}/${day} ${hours}:${minutes}:${seconds}`); // "2023/10/05 14:30:45" // 月/日/年 console.log(`${month}/${day}/${year}`); // "10/05/2023" // 日-月-年 console.log(`${day}-${month}-${year}`); // "05-10-2023"
3. 相對時間
const now = new Date(); const past = new Date(now - 5 * 60 * 1000); // 5分鐘前 const future = new Date(now + 2 * 24 * 60 * 60 * 1000); // 2天后 // 相對時間計算 function formatRelativeTime(date) { const diff = Math.round((date - now) / 1000); // 時間差(秒) if (diff < 60) return `${diff}秒${diff > 0 ? '后' : '前'}`; if (diff < 3600) return `${Math.floor(diff / 60)}分鐘${diff > 0 ? '后' : '前'}`; if (diff < 86400) return `${Math.floor(diff / 3600)}小時${diff > 0 ? '后' : '前'}`; return `${Math.floor(diff / 86400)}天${diff > 0 ? '后' : '前'}`; } console.log(formatRelativeTime(past)); // "5分鐘前" console.log(formatRelativeTime(future)); // "2天后"
4. 時間拼接
const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); const day = String(now.getDate()).padStart(2, '0'); const hours = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); // 拼接成文件名格式 console.log(`log_${year}${month}${day}_${hours}${minutes}${seconds}.txt`); // "log_20231005_143045.txt" // 拼接成日志格式 console.log(`[${year}-${month}-${day} ${hours}:${minutes}:${seconds}] INFO: Hello World`); // "[2023-10-05 14:30:45] INFO: Hello World"
5. 時區(qū)轉換
const now = new Date(); // 轉換為紐約時間 console.log(now.toLocaleString('en-US', { timeZone: 'America/New_York' })); // "10/5/2023, 2:30:45 AM" // 轉換為東京時間 console.log(now.toLocaleString('ja-JP', { timeZone: 'Asia/Tokyo' })); // "2023/10/5 15:30:45"
6. 時間戳格式化
const timestamp = Date.now(); // 時間戳轉日期 const date = new Date(timestamp); console.log(date.toLocaleString()); // "2023/10/5 14:30:45" // 時間戳轉自定義格式 const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; console.log(formattedDate); // "2023-10-05"
7. 高級格式化(Intl.DateTimeFormat
)
const now = new Date(); // 中文格式 console.log(new Intl.DateTimeFormat('zh-CN', { dateStyle: 'full', timeStyle: 'long' }).format(now)); // "2023年10月5日星期四 14:30:45 GMT+8" // 英文格式 console.log(new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeStyle: 'short' }).format(now)); // "Oct 5, 2023, 2:30 PM" // 自定義格式 console.log(new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true }).format(now)); // "Oct 05, 2023, 02:30:45 PM"
8. 時間差計算
const start = new Date('2023-10-01T00:00:00'); const end = new Date('2023-10-05T12:00:00'); // 計算時間差(毫秒) const diff = end - start; // 轉換為天、小時、分鐘、秒 const days = Math.floor(diff / (1000 * 60 * 60 * 24)); const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((diff % (1000 * 60)) / 1000); console.log(`${days}天 ${hours}小時 ${minutes}分鐘 ${seconds}秒`); // "4天 12小時 0分鐘 0秒"
9. 使用第三方庫(Day.js)
const dayjs = require('dayjs'); // 格式化 console.log(dayjs().format('YYYY-MM-DD HH:mm:ss')); // "2023-10-05 14:30:45" // 相對時間 console.log(dayjs().from(dayjs('2023-10-01'))); // "4天前" // 時間差 console.log(dayjs('2023-10-05').diff(dayjs('2023-10-01'), 'day')); // 4
10. 其他格式
const now = new Date(); // 12小時制 console.log(now.toLocaleString('en-US', { hour12: true })); // "10/5/2023, 2:30:45 PM" // 24小時制 console.log(now.toLocaleString('en-US', { hour12: false })); // "10/5/2023, 14:30:45" // 僅日期(短格式) console.log(now.toLocaleDateString('en-US', { dateStyle: 'short' })); // "10/5/23" // 僅時間(短格式) console.log(now.toLocaleTimeString('en-US', { timeStyle: 'short' })); // "2:30 PM"
總結
JavaScript 提供了豐富的 API 來處理日期和時間,從基礎的 Date
對象到高級的 Intl.DateTimeFormat
,可以滿足大多數場景的需求。通過本文的介紹,你應該能夠掌握如何使用 JavaScript 生成各種時間格式,并進行時間計算和時區(qū)轉換。對于更復雜的需求,可以考慮使用第三方庫來簡化操作。
到此這篇關于JavaScrip時間格式整理大全的文章就介紹到這了,更多相關JS時間格式大全內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
TypeScript工具類 Partial 和 Required 的場景分析
這篇文章主要介紹了TypeScript工具類 Partial 和 Required 的詳細講解,本文通過場景描述給大家詳細講解工具類的使用,結合實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-09-09如何利用Web Speech API之speechSynthesis實現(xiàn)文字轉語音功能
Web Speech API使你能夠將語音數據合并到Web應用程序中,SpeechSynthesisUtterance是HTML5中新增的API,用于將指定文字合成為對應的語音,這篇文章主要介紹了利用Web Speech API之speechSynthesis實現(xiàn)文字轉語音功能,需要的朋友可以參考下2024-06-06小程序websocket心跳庫(websocket-heartbeat-miniprogram)
這篇文章主要介紹了小程序websocket心跳庫(websocket-heartbeat-miniprogram),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02