亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript時間格式整理大全(附大量示例)

 更新時間:2025年04月03日 10:21:30   作者:oil歐喲  
在JavaScript中時間格式轉換是一個常見的需求,可以通過多種方式實現(xiàn),這篇文章主要介紹了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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • JS實現(xiàn)的網頁倒計時數字時鐘效果

    JS實現(xiàn)的網頁倒計時數字時鐘效果

    這篇文章主要介紹了JS實現(xiàn)的網頁倒計時數字時鐘效果,是一款非常實用的javascript倒計時特效,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-03-03
  • TypeScript工具類 Partial 和 Required 的場景分析

    TypeScript工具類 Partial 和 Required 的場景分析

    這篇文章主要介紹了TypeScript工具類 Partial 和 Required 的詳細講解,本文通過場景描述給大家詳細講解工具類的使用,結合實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2022-09-09
  • 如何用JS判斷數組中是否存在某個值或者某個對象的值

    如何用JS判斷數組中是否存在某個值或者某個對象的值

    數組是我們編程中經常使用的的數據結構之一,在處理數組時,我們經常需要在數組中查找特定的值,下面這篇文章主要給大家介紹了關于如何用JS判斷數組中是否存在某個值或者某個對象的值的相關資料,需要的朋友可以參考下
    2023-01-01
  • 微信小程序實現(xiàn)簡單秒表設計

    微信小程序實現(xiàn)簡單秒表設計

    這篇文章主要為大家詳細介紹了微信小程序實現(xiàn)簡單秒表設計,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-09-09
  • three.js創(chuàng)建樓層布局圖的示例代碼

    three.js創(chuàng)建樓層布局圖的示例代碼

    本文主要介紹了three.js創(chuàng)建樓層布局圖的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-07-07
  • 如何利用Web Speech API之speechSynthesis實現(xiàn)文字轉語音功能

    如何利用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)

    這篇文章主要介紹了小程序websocket心跳庫(websocket-heartbeat-miniprogram),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-02-02
  • ie 處理 gif動畫 的onload 事件的一個 bug

    ie 處理 gif動畫 的onload 事件的一個 bug

    ie 處理 gif動畫 的onload 事件的一個 bug...
    2007-04-04
  • JavaScript中的函數(二)

    JavaScript中的函數(二)

    函數是由事件驅動的或者當它被調用時執(zhí)行的可重復使用的代碼塊。本文給大家介紹介紹javascript中的函數(二),對javascript函數相關知識感興趣的朋友一起學習吧
    2015-12-12
  • JavaScript經典案例之簡易計算器

    JavaScript經典案例之簡易計算器

    這篇文章主要為大家詳細介紹了JavaScript經典案例之簡易計算器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-08-08

最新評論