最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript時區(qū)時間轉(zhuǎn)換幾種實現(xiàn)方法

 更新時間:2025年06月04日 09:42:13   作者:黑匣子~  
在前端開發(fā)過程中,關(guān)于時間相關(guān)的業(yè)務(wù)處理是非常常見的需求,這篇文章主要介紹了JavaScript時區(qū)時間轉(zhuǎn)換幾種實現(xiàn)方法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

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支持 QDogggg 等高級格式化符號? 可選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'
isoWeekISO 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)文章

最新評論

拜城县| 苗栗县| 樟树市| 长海县| 金门县| 日喀则市| 龙岩市| 息烽县| 大埔县| 治多县| 句容市| 新宁县| 安福县| 弋阳县| 桂东县| 三明市| 鄱阳县| 榆社县| 类乌齐县| 宜宾市| 东山县| 石景山区| 曲阳县| 绿春县| 钦州市| 阿拉善盟| 丹凤县| 大荔县| 峨眉山市| 正阳县| 奈曼旗| 南部县| 泰顺县| 清水河县| 青神县| 新绛县| 岳阳县| 图木舒克市| 江陵县| 临洮县| 亳州市|