You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript将UTC时间转换为用户本地时区?

将UTC时间转换为用户本地时区(JavaScript实现)

一、原生JavaScript实现(无需额外包)

JavaScript的Date对象本身支持UTC时间转换为本地时区,解析UTC字符串后,通过toLocaleString系列方法即可输出本地时区的时间:

const utcTime = '2023-02-01T17:00:22.127Z';
const date = new Date(utcTime);

// 输出默认格式的本地时间
console.log(date.toLocaleString());

// 自定义输出格式(包含时区名称)
const formatOptions = {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  timeZoneName: 'short'
};
console.log(date.toLocaleString(undefined, formatOptions));

toLocaleString默认会自动使用当前用户的本地时区,无需手动指定时区信息,这是最简便的实现方式。

二、结合jstz包的正确用法

jstz的核心作用是检测用户的时区标识符(如Asia/Shanghai),时间转换仍需依赖原生Date对象的格式化方法,正确用法如下:

// 获取用户的时区标识符
const userTimeZone = jstz.determine().name();

const utcTime = '2023-02-01T17:00:22.127Z';
const date = new Date(utcTime);

// 传入时区信息进行格式化
const formatOptions = {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  timeZone: userTimeZone,
  timeZoneName: 'long'
};
console.log(date.toLocaleString(undefined, formatOptions));

内容的提问来源于stack exchange,提问作者user12763413

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 14:35:21