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插件处理时区之间的转换。
- 引入安装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
- 调用方法:
$dayjs.unix(time).tz('America/Sao_Paulo').format('YY-MM-DD')
time为需要处理的时间,比如后端返回过来的,先通过unix转为时间戳,再进行时区转换,最后格式化。dayjs中有很多常用的插件,像上面使用到的utc、timezone,还有unix,都在官网上可以自行查看。
-
上面我没有用到UTC这个插件为什么还要安装呢?
因为dayjs/plugin/timezone 插件依赖 dayjs/plugin/utc 插件,timezone 插件的内部原理是:
它先把你的本地时间或字符串转成 UTC,再从 UTC 偏移到目标时区。
如果你不引入 utc 插件,tz() 无法完成转换,会报错或无效。
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 | 支持 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 | 获取/设置某日期为第几周 | ❕特定场景 | import weekOfYear from 'dayjs/plugin/weekOfYear' |
isoWeek | ISO 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() |