javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > js时区时间转换

JavaScript时区时间转换几种实现方法

作者:黑匣子~

在前端开发过程中,关于时间相关的业务处理是非常常见的需求,这篇文章主要介绍了JavaScript时区时间转换几种实现方法,文中通过代码介绍的非常详细,需要的朋友可以参考下

js时区时间转换

js中获取当前时间,默认是东八区时间,如果需要转换成其他时区,可以通过以下方法实现。

方法1:根据时区重组格式

const item = timeZoneList.filter((item) => item.label === area)

timeZoneList 是你自己维护的区域/时区映射列表,例如:

const timeZoneList = [
  { label: 'BRL', value: 'America/Sao_Paulo' },
  { label: 'EST', value: 'America/New_York' }
];

对应时区的时区id可点击此处查看传送门

通过 area(如 ‘BRL’)从中获取对应的 IANA 时区名称(如 ‘America/Sao_Paulo’);

const date = new Date(timestamp * 1000)

将秒级时间戳转换为 Date 对象(JavaScript 中时间戳是毫秒);

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'
})

使用 Intl.DateTimeFormat API 按照指定时区格式化日期;
en-CA 是语言/地区标识,格式类似于 2025-05-08 22:15:30;

const parts = formatter.formatToParts(date)

将格式化结果拆解为结构化的时间片段,例如:

[
  { type: 'year', value: '2025' },
  { type: 'month', value: '05' },
  ...
]

然后用 find 取出每一部分,拼接成你想要的格式:

const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`

完整的代码如下

// 定义时区列表
const timeZoneList = [
  { label: 'BRL', value: 'America/Sao_Paulo' },
  { label: 'EST', value: 'America/New_York' }
  // 其他时区可以继续添加
]
/**
 * 格式化时间戳为指定时区的日期时间
 * @param {number} timestamp 时间戳(毫秒)
 * @param {string} area 区域 "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 {
    // 将时间戳转换为对应时区时间
    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}`
  }
}

调用方法如下:

formatTimestampToTimeZone(1715188400, 'BRL')

方法2:使用dayjs处理

dayjs有一个插件是专门处理时区之间的转换的插件名称为Timezone,官方地址

下面我以在vue上引入的代码为例,展示如何使用dayjs插件处理时区之间的转换。

npm install dayjs
npm install dayjs-plugin-utc dayjs-plugin-timezone
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
$dayjs.unix(time).tz('America/Sao_Paulo').format('YY-MM-DD')

time为需要处理的时间,比如后端返回过来的,先通过unix转为时间戳,再进行时区转换,最后格式化。dayjs中有很多常用的插件,像上面使用到的utc、timezone,还有unix,都在官网上可以自行查看。

Day.js 常用插件与方法速查表

插件汇总

插件名用途说明是否常用示例引入方式
utc解析和格式化 UTC 时间✅ 必须import utc from 'dayjs/plugin/utc'
timezone支持时区转换(需依赖 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获取/设置某日期为第几周❕特定场景import weekOfYear from 'dayjs/plugin/weekOfYear'
isoWeekISO 8601 的周数处理❕特定场景import isoWeek from 'dayjs/plugin/isoWeek'

方法速查表

方法名用途示例
dayjs()获取当前时间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)获取某单位结束时间dayjs().endOf('year')
.unix()获取 Unix 时间戳(秒)dayjs().unix()
.valueOf()获取时间戳(毫秒)dayjs().valueOf()
.tz(timeZone)转换到指定时区dayjs().tz('Asia/Tokyo')
.fromNow()距离现在的相对时间dayjs().subtract(3, 'day').fromNow()
.toNow()当前时间与目标时间之间dayjs().toNow()

总结 

到此这篇关于JavaScript时区时间转换几种实现方法的文章就介绍到这了,更多相关js时区时间转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文