欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2025年04月03日 10:21:30   作者:oil歐喲  
在JavaScript中時(shí)間格式轉(zhuǎn)換是一個(gè)常見的需求,可以通過多種方式實(shí)現(xiàn),這篇文章主要介紹了JavaScript時(shí)間格式的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

前言

在 JS 中,處理時(shí)間和日期是常見的需求。無論是展示當(dāng)前時(shí)間、格式化日期字符串,還是進(jìn)行時(shí)間計(jì)算,JavaScript 都提供了豐富的 API 來滿足這些需求。本文將詳細(xì)介紹如何使用 JavaScript 生成各種時(shí)間格式,從基礎(chǔ)到高級,涵蓋常見的場景。內(nèi)容比較多,請大家搭配目錄食用。

基礎(chǔ)時(shí)間獲取

1.1 獲取當(dāng)前時(shí)間

JavaScript 提供了 Date 對象來處理日期和時(shí)間。要獲取當(dāng)前時(shí)間,只需創(chuàng)建一個(gè) Date 對象即可:

const now = new Date();
console.log(now); // 輸出當(dāng)前時(shí)間的完整日期和時(shí)間

1.2 獲取時(shí)間戳

時(shí)間戳表示從 1970 年 1 月 1 日 00:00:00 UTC 到當(dāng)前時(shí)間的毫秒數(shù)。可以使用 getTime() 方法或 Date.now() 來獲取時(shí)間戳:

const timestamp1 = new Date().getTime();
const timestamp2 = Date.now();
console.log(timestamp1, timestamp2); // 輸出當(dāng)前時(shí)間的時(shí)間戳

時(shí)間格式化

2.1 使用 toLocaleString() 格式化時(shí)間

toLocaleString() 方法可以根據(jù)本地化設(shè)置格式化日期和時(shí)間:

const now = new Date();
console.log(now.toLocaleString()); // 輸出本地化的日期和時(shí)間
console.log(now.toLocaleDateString()); // 輸出本地化的日期
console.log(now.toLocaleTimeString()); // 輸出本地化的時(shí)間

2.2 自定義格式化

如果需要更靈活的格式化,可以手動(dòng)拼接日期和時(shí)間的各個(gè)部分:

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); // 輸出格式化的時(shí)間,如 "14:30:45"
console.log(formattedDateTime); // 輸出格式化的日期和時(shí)間,如 "2023-10-05 14:30:45"

2.3 使用 Intl.DateTimeFormat 進(jìn)行高級格式化

Intl.DateTimeFormat 對象提供了更強(qiáng)大的本地化日期和時(shí)間格式化功能:

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小時(shí)制
});

console.log(formatter.format(now)); // 輸出格式化的日期和時(shí)間,如 "2023/10/05 14:30:45"

時(shí)間計(jì)算

3.1 時(shí)間加減

可以通過修改 Date 對象的各個(gè)部分來進(jìn)行時(shí)間加減:

const now = new Date();
now.setHours(now.getHours() + 1); // 當(dāng)前時(shí)間加1小時(shí)
now.setDate(now.getDate() + 7); // 當(dāng)前日期加7天
console.log(now);

3.2 計(jì)算時(shí)間差

可以通過時(shí)間戳來計(jì)算兩個(gè)時(shí)間點(diǎn)之間的差值:

const start = new Date('2023-10-01T00:00:00');
const end = new Date('2023-10-05T12:00:00');
const diffInMilliseconds = end - start; // 時(shí)間差,單位為毫秒
const diffInSeconds = diffInMilliseconds / 1000;
const diffInMinutes = diffInSeconds / 60;
const diffInHours = diffInMinutes / 60;
const diffInDays = diffInHours / 24;

console.log(diffInDays); // 輸出時(shí)間差,如 "4.5" 天

時(shí)區(qū)處理

4.1 獲取當(dāng)前時(shí)區(qū)

可以使用 Intl.DateTimeFormat 獲取當(dāng)前時(shí)區(qū):

const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(timeZone); // 輸出當(dāng)前時(shí)區(qū),如 "Asia/Shanghai"

4.2 轉(zhuǎn)換時(shí)區(qū)

可以使用 toLocaleString() 或 Intl.DateTimeFormat 來轉(zhuǎn)換時(shí)區(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)); // 輸出紐約時(shí)間,如 "10/05/2023 02:30:45"

第三方庫推薦

雖然 JavaScript 原生的 Date 對象已經(jīng)足夠強(qiáng)大,但在處理復(fù)雜的日期和時(shí)間操作時(shí),使用第三方庫可以更加方便。以下是幾個(gè)常用的日期處理庫:

  • Moment.js: 功能強(qiáng)大,但體積較大,推薦使用其替代品。
  • Day.js: Moment.js 的輕量級替代品,API 兼容,體積小。
  • date-fns: 模塊化設(shè)計(jì),按需引入,功能豐富。
// 使用 Day.js 格式化時(shí)間
const dayjs = require('dayjs');
console.log(dayjs().format('YYYY-MM-DD HH:mm:ss')); // 輸出格式化的日期和時(shí)間

常用的格式示例

1. 基礎(chǔ)時(shí)間格式

const now = new Date();

// 完整日期和時(shí)間
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"

// 本地日期和時(shí)間
console.log(now.toLocaleString()); // "2023/10/5 14:30:45" (根據(jù)本地化設(shè)置)

// 本地日期
console.log(now.toLocaleDateString()); // "2023/10/5"

// 本地時(shí)間
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"

// 時(shí):分:秒
console.log(`${hours}:${minutes}:${seconds}`); // "14:30:45"

// 年/月/日 時(shí):分:秒
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. 相對時(shí)間

const now = new Date();
const past = new Date(now - 5 * 60 * 1000); // 5分鐘前
const future = new Date(now + 2 * 24 * 60 * 60 * 1000); // 2天后

// 相對時(shí)間計(jì)算
function formatRelativeTime(date) {
  const diff = Math.round((date - now) / 1000); // 時(shí)間差(秒)
  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)}小時(shí)${diff > 0 ? '后' : '前'}`;
  return `${Math.floor(diff / 86400)}天${diff > 0 ? '后' : '前'}`;
}

console.log(formatRelativeTime(past)); // "5分鐘前"
console.log(formatRelativeTime(future)); // "2天后"

4. 時(shí)間拼接

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. 時(shí)區(qū)轉(zhuǎn)換

const now = new Date();

// 轉(zhuǎn)換為紐約時(shí)間
console.log(now.toLocaleString('en-US', { timeZone: 'America/New_York' })); // "10/5/2023, 2:30:45 AM"

// 轉(zhuǎn)換為東京時(shí)間
console.log(now.toLocaleString('ja-JP', { timeZone: 'Asia/Tokyo' })); // "2023/10/5 15:30:45"

6. 時(shí)間戳格式化

const timestamp = Date.now();

// 時(shí)間戳轉(zhuǎn)日期
const date = new Date(timestamp);
console.log(date.toLocaleString()); // "2023/10/5 14:30:45"

// 時(shí)間戳轉(zhuǎn)自定義格式
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. 時(shí)間差計(jì)算

const start = new Date('2023-10-01T00:00:00');
const end = new Date('2023-10-05T12:00:00');

// 計(jì)算時(shí)間差(毫秒)
const diff = end - start;

// 轉(zhuǎn)換為天、小時(shí)、分鐘、秒
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}小時(shí) ${minutes}分鐘 ${seconds}秒`); // "4天 12小時(shí) 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"

// 相對時(shí)間
console.log(dayjs().from(dayjs('2023-10-01'))); // "4天前"

// 時(shí)間差
console.log(dayjs('2023-10-05').diff(dayjs('2023-10-01'), 'day')); // 4

10. 其他格式

const now = new Date();

// 12小時(shí)制
console.log(now.toLocaleString('en-US', { hour12: true })); // "10/5/2023, 2:30:45 PM"

// 24小時(shí)制
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"

// 僅時(shí)間(短格式)
console.log(now.toLocaleTimeString('en-US', { timeStyle: 'short' })); // "2:30 PM"

總結(jié)

JavaScript 提供了豐富的 API 來處理日期和時(shí)間,從基礎(chǔ)的 Date 對象到高級的 Intl.DateTimeFormat,可以滿足大多數(shù)場景的需求。通過本文的介紹,你應(yīng)該能夠掌握如何使用 JavaScript 生成各種時(shí)間格式,并進(jìn)行時(shí)間計(jì)算和時(shí)區(qū)轉(zhuǎn)換。對于更復(fù)雜的需求,可以考慮使用第三方庫來簡化操作。

到此這篇關(guān)于JavaScrip時(shí)間格式整理大全的文章就介紹到這了,更多相關(guān)JS時(shí)間格式大全內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • JS實(shí)現(xiàn)的網(wǎng)頁倒計(jì)時(shí)數(shù)字時(shí)鐘效果

    JS實(shí)現(xiàn)的網(wǎng)頁倒計(jì)時(shí)數(shù)字時(shí)鐘效果

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

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

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

    如何用JS判斷數(shù)組中是否存在某個(gè)值或者某個(gè)對象的值

    數(shù)組是我們編程中經(jīng)常使用的的數(shù)據(jù)結(jié)構(gòu)之一,在處理數(shù)組時(shí),我們經(jīng)常需要在數(shù)組中查找特定的值,下面這篇文章主要給大家介紹了關(guān)于如何用JS判斷數(shù)組中是否存在某個(gè)值或者某個(gè)對象的值的相關(guān)資料,需要的朋友可以參考下
    2023-01-01
  • 微信小程序?qū)崿F(xiàn)簡單秒表設(shè)計(jì)

    微信小程序?qū)崿F(xiàn)簡單秒表設(shè)計(jì)

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

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

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

    如何利用Web Speech API之speechSynthesis實(shí)現(xiàn)文字轉(zhuǎn)語音功能

    Web Speech API使你能夠?qū)⒄Z音數(shù)據(jù)合并到Web應(yīng)用程序中,SpeechSynthesisUtterance是HTML5中新增的API,用于將指定文字合成為對應(yīng)的語音,這篇文章主要介紹了利用Web Speech API之speechSynthesis實(shí)現(xiàn)文字轉(zhuǎn)語音功能,需要的朋友可以參考下
    2024-06-06
  • 小程序websocket心跳庫(websocket-heartbeat-miniprogram)

    小程序websocket心跳庫(websocket-heartbeat-miniprogram)

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

    ie 處理 gif動(dòng)畫 的onload 事件的一個(gè) bug

    ie 處理 gif動(dòng)畫 的onload 事件的一個(gè) bug...
    2007-04-04
  • JavaScript中的函數(shù)(二)

    JavaScript中的函數(shù)(二)

    函數(shù)是由事件驅(qū)動(dòng)的或者當(dāng)它被調(diào)用時(shí)執(zhí)行的可重復(fù)使用的代碼塊。本文給大家介紹介紹javascript中的函數(shù)(二),對javascript函數(shù)相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧
    2015-12-12
  • JavaScript經(jīng)典案例之簡易計(jì)算器

    JavaScript經(jīng)典案例之簡易計(jì)算器

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

最新評論