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

如何使用dayjs将指定时区的日期字符串格式化显示?

使用Day.js转换ISO时间格式为指定样式

要把YYYY-MM-DDTHH:mm:ssZ格式的时间转换成2023-04-30 04:00 PM EST样式,需要借助Day.js的几个插件来实现时区和高级格式化支持,步骤如下:

1. 安装依赖插件

Day.js默认不支持时区处理和部分高级格式符,需要安装以下插件:

npm install dayjs dayjs/plugin/utc dayjs/plugin/timezone dayjs/plugin/advanced-format

如果是通过CDN引入,需添加对应脚本:

<script src="https://unpkg.com/dayjs@1.11.10/dayjs.min.js"></script>
<script src="https://unpkg.com/dayjs@1.11.10/plugin/utc.js"></script>
<script src="https://unpkg.com/dayjs@1.11.10/plugin/timezone.js"></script>
<script src="https://unpkg.com/dayjs@1.11.10/plugin/advancedFormat.js"></script>

2. 代码实现

// 启用所需插件
dayjs.extend(dayjs_plugin_utc) // CDN引入时用此写法,npm引入则用require方式
dayjs.extend(dayjs_plugin_timezone)
dayjs.extend(dayjs_plugin_advancedFormat)

// 原始时间字符串
const rawTime = '2023-04-30T16:00:00-05:00'

// 转换并格式化
const formattedTime = dayjs(rawTime)
  .tz('America/New_York') // 指定对应时区的IANA标识符,Day.js会自动识别EST/EDT
  .format('YYYY-MM-DD hh:mm A z')

console.log(formattedTime) // 输出:2023-04-30 04:00 PM EST

关键说明

  • 时区处理:必须使用America/New_York这类IANA时区标识符,而非直接写EST,这样Day.js能自动根据日期切换夏令时(EDT)和冬令时(EST)。
  • 格式符解析:
    • hh:12小时制的小时(带前导零)
    • A:大写的AM/PM标识
    • z:时区缩写(如EST/EDT)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:15:02