JavaScript時區(qū)時間轉(zhuǎn)換幾種實現(xiàn)方法
js時區(qū)時間轉(zhuǎn)換
js中獲取當(dāng)前時間,默認(rèn)是東八區(qū)時間,如果需要轉(zhuǎn)換成其他時區(qū),可以通過以下方法實現(xiàn)。
方法1:根據(jù)時區(qū)重組格式
- 第一步:匹配時區(qū)
const item = timeZoneList.filter((item) => item.label === area)
timeZoneList 是你自己維護的區(qū)域/時區(qū)映射列表,例如:
const timeZoneList = [
{ label: 'BRL', value: 'America/Sao_Paulo' },
{ label: 'EST', value: 'America/New_York' }
];
對應(yīng)時區(qū)的時區(qū)id可點擊此處查看傳送門

通過 area(如 ‘BRL’)從中獲取對應(yīng)的 IANA 時區(qū)名稱(如 ‘America/Sao_Paulo’);
- 第二步:格式化時間
const date = new Date(timestamp * 1000)
將秒級時間戳轉(zhuǎn)換為 Date 對象(JavaScript 中時間戳是毫秒);
const options = { timeZone, hour12: false }
設(shè)置目標(biāo)時區(qū),并關(guān)閉 12 小時制(確保是 24 小時制);
const formatter = new Intl.DateTimeFormat('en-CA', {
...options,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
使用 Intl.DateTimeFormat API 按照指定時區(qū)格式化日期;
en-CA 是語言/地區(qū)標(biāo)識,格式類似于 2025-05-08 22:15:30;
- 第三步:重組格式
const parts = formatter.formatToParts(date)
將格式化結(jié)果拆解為結(jié)構(gòu)化的時間片段,例如:
[
{ type: 'year', value: '2025' },
{ type: 'month', value: '05' },
...
]
然后用 find 取出每一部分,拼接成你想要的格式:
const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`
完整的代碼如下
// 定義時區(qū)列表
const timeZoneList = [
{ label: 'BRL', value: 'America/Sao_Paulo' },
{ label: 'EST', value: 'America/New_York' }
// 其他時區(qū)可以繼續(xù)添加
]
/**
* 格式化時間戳為指定時區(qū)的日期時間
* @param {number} timestamp 時間戳(毫秒)
* @param {string} area 區(qū)域 "BRL")
* @returns {string} 格式化后的日期時間字符串
*/
export function formatTimestampToTimeZone(timestamp, area = 'BRL') {
let timeZone = ''
if (area) {
const item = timeZoneList.filter((item) => item.label === area)
if (!item.length) return
timeZone = item[0].value
}
if (!timestamp || !timeZone) {
return 'Invalid input: timestamp and timeZone are required.'
}
try {
// 將時間戳轉(zhuǎn)換為對應(yīng)時區(qū)時間
const date = new Date(timestamp * 1000)
const options = { timeZone, hour12: false } // 禁用 12 小時制,確保 24 小時制
const formatter = new Intl.DateTimeFormat('en-CA', {
...options,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
// 獲取格式化后的日期時間字符串
const parts = formatter.formatToParts(date)
console.log(parts)
// 提取日期和時間部分并重新組合為 "年-月-日 時:分:秒" 格式
const formattedDate = `${parts.find((p) => p.type === 'year').value}-${
parts.find((p) => p.type === 'month').value
}-${parts.find((p) => p.type === 'day').value} ${parts.find((p) => p.type === 'hour').value}:${parts.find((p) => p.type === 'minute').value}:${
parts.find((p) => p.type === 'second').value
}`
return formattedDate
} catch (error) {
return `Error: ${error.message}`
}
}
調(diào)用方法如下:
formatTimestampToTimeZone(1715188400, 'BRL')
方法2:使用dayjs處理
dayjs有一個插件是專門處理時區(qū)之間的轉(zhuǎn)換的插件名稱為Timezone,官方地址
下面我以在vue上引入的代碼為例,展示如何使用dayjs插件處理時區(qū)之間的轉(zhuǎn)換。
- 引入安裝dayjs插件:
npm install dayjs npm install dayjs-plugin-utc dayjs-plugin-timezone
- 在main.js中引入dayjs插件:
import dayjs from 'dayjs' // 引入插件 import utc from 'dayjs/plugin/utc' import timezone from 'dayjs/plugin/timezone' // 安裝插件 dayjs.extend(utc) dayjs.extend(timezone)
我這邊因為很多地方用到了,所以掛載到全局上了
const app = createApp(App); app.config.globalProperties.$dayjs = dayjs
- 調(diào)用方法:
$dayjs.unix(time).tz('America/Sao_Paulo').format('YY-MM-DD')
time為需要處理的時間,比如后端返回過來的,先通過unix轉(zhuǎn)為時間戳,再進行時區(qū)轉(zhuǎn)換,最后格式化。dayjs中有很多常用的插件,像上面使用到的utc、timezone,還有unix,都在官網(wǎng)上可以自行查看。
上面我沒有用到UTC這個插件為什么還要安裝呢?
因為dayjs/plugin/timezone 插件依賴 dayjs/plugin/utc 插件,timezone 插件的內(nèi)部原理是:
它先把你的本地時間或字符串轉(zhuǎn)成 UTC,再從 UTC 偏移到目標(biāo)時區(qū)。
如果你不引入 utc 插件,tz() 無法完成轉(zhuǎn)換,會報錯或無效。
Day.js 常用插件與方法速查表
插件匯總
| 插件名 | 用途說明 | 是否常用 | 示例引入方式 |
|---|---|---|---|
utc | 解析和格式化 UTC 時間 | ? 必須 | import utc from 'dayjs/plugin/utc' |
timezone | 支持時區(qū)轉(zhuǎn)換(需依賴 utc) | ? 必須 | import timezone from 'dayjs/plugin/timezone' |
relativeTime | 支持“幾分鐘前”、“幾天前”等格式 | ? 常用 | import relativeTime from 'dayjs/plugin/relativeTime' |
localizedFormat | 使用本地化格式(如 LLL) | ? 常用 | import localizedFormat from 'dayjs/plugin/localizedFormat' |
isSameOrBefore | 比較時間是否早于或相等 | ? 常用 | import isSameOrBefore from 'dayjs/plugin/isSameOrBefore' |
isSameOrAfter | 比較時間是否晚于或相等 | ? 常用 | import isSameOrAfter from 'dayjs/plugin/isSameOrAfter' |
advancedFormat | 支持 Q, Do, gggg 等高級格式化符號 | ? 可選 | import advancedFormat from 'dayjs/plugin/advancedFormat' |
duration | 操作時間間隔,如 2 小時 30 分鐘 | ? 常用 | import duration from 'dayjs/plugin/duration' |
customParseFormat | 自定義時間解析格式 | ? 常用 | import customParseFormat from 'dayjs/plugin/customParseFormat' |
weekOfYear | 獲取/設(shè)置某日期為第幾周 | ?特定場景 | import weekOfYear from 'dayjs/plugin/weekOfYear' |
isoWeek | ISO 8601 的周數(shù)處理 | ?特定場景 | import isoWeek from 'dayjs/plugin/isoWeek' |
方法速查表
| 方法名 | 用途 | 示例 |
|---|---|---|
dayjs() | 獲取當(dāng)前時間 | dayjs().format() |
dayjs(value) | 解析時間(支持字符串、時間戳等) | dayjs('2025-05-08') |
.format(pattern) | 格式化日期為字符串 | dayjs().format('YYYY-MM-DD HH:mm:ss') |
.add(n, unit) | 增加時間 | dayjs().add(7, 'day') |
.subtract(n, unit) | 減少時間 | dayjs().subtract(1, 'month') |
.diff(date, unit) | 比較兩個時間差 | dayjs().diff(otherDate, 'day') |
.isBefore(date) | 是否早于指定時間 | dayjs().isBefore('2025-01-01') |
.isAfter(date) | 是否晚于指定時間 | dayjs().isAfter('2025-01-01') |
.isSame(date, unit) | 是否相同(按單位) | dayjs().isSame('2025-05-08', 'day') |
.startOf(unit) | 獲取某單位開始時間 | dayjs().startOf('month') |
.endOf(unit) | 獲取某單位結(jié)束時間 | dayjs().endOf('year') |
.unix() | 獲取 Unix 時間戳(秒) | dayjs().unix() |
.valueOf() | 獲取時間戳(毫秒) | dayjs().valueOf() |
.tz(timeZone) | 轉(zhuǎn)換到指定時區(qū) | dayjs().tz('Asia/Tokyo') |
.fromNow() | 距離現(xiàn)在的相對時間 | dayjs().subtract(3, 'day').fromNow() |
.toNow() | 當(dāng)前時間與目標(biāo)時間之間 | dayjs().toNow() |
總結(jié)
到此這篇關(guān)于JavaScript時區(qū)時間轉(zhuǎn)換幾種實現(xiàn)方法的文章就介紹到這了,更多相關(guān)js時區(qū)時間轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
輕松玩轉(zhuǎn)BootstrapTable(后端使用SpringMVC+Hibernate)
這篇文章主要和大家輕松玩轉(zhuǎn)BootstrapTable,后端使用SpringMVC+Hibernate,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09
JS實現(xiàn)將圖片轉(zhuǎn)為base64格式
Base64是一種用64個字符來表示任意二進制數(shù)據(jù)的方法,這篇文章主要為大家介紹了如何實現(xiàn)將圖片轉(zhuǎn)為base64格式,感興趣的小伙伴可以學(xué)習(xí)一下2023-07-07
javascript實現(xiàn)狀態(tài)欄文字首尾相接循環(huán)滾動的方法
這篇文章主要介紹了javascript實現(xiàn)狀態(tài)欄文字首尾相接循環(huán)滾動的方法,實例分析了javascript定時函數(shù)及頁面元素屬性操作的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07
小程序開發(fā)調(diào)用微信支付以及微信回調(diào)地址配置
本文主要介紹了小程序開發(fā)調(diào)用微信支付以及微信回調(diào)地址配置,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05

