在特定时区格式化日期

2022-01-16 00:00:00 timezone javascript momentjs

我正在使用 Moment.js 在我的网络应用程序中解析和格式化日期.作为 JSON 对象的一部分,我的后端服务器以 UTC 纪元(Unix 偏移量)的毫秒数发送日期.

I'm using Moment.js to parse and format dates in my web app. As part of a JSON object, my backend server sends dates as a number of milliseconds from the UTC epoch (Unix offset).

在特定时区解析日期很容易——只需在解析前将 RFC 822 时区标识符附加到字符串的末尾即可:

Parsing dates in a specific timezone is easy -- just append the RFC 822 timezone identifier to the end of the string before parsing:

// response varies according to your timezone
const m1 = moment('3/11/2012 13:00').utc().format("MM/DD HH:mm")

// problem solved, always "03/11 17:00"
const m2 = moment('3/11/2012 13:00 -0400').utc().format("MM/DD HH:mm")

console.log({ m1, m2 })

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

但是如何在特定时区格式化日期?

无论浏览器的当前时间如何,我都想要一致的结果,但我不想以 UTC 显示日期.

I want consistent results regardless of the browser's current time, but I don't want to display dates in UTC.

推荐答案

正如Manto's answer中指出的,.utcOffset() 是 Moment 的首选方法2.9.0.此函数使用与 UTC 的实际偏移量,而不是反向偏移量(例如,DST 期间的纽约为 -240).像+0400"这样的偏移字符串的工作方式和以前一样:

As pointed out in Manto's answer, .utcOffset() is the preferred method as of Moment 2.9.0. This function uses the real offset from UTC, not the reverse offset (e.g., -240 for New York during DST). Offset strings like "+0400" work the same as before:

// always "2013-05-23 00:55"
moment(1369266934311).utcOffset(60).format('YYYY-MM-DD HH:mm')
moment(1369266934311).utcOffset('+0100').format('YYYY-MM-DD HH:mm')

较旧的 .zone() 作为二传手在 Moment.js 2.9.0 中被弃用.它接受包含时区标识符的字符串(例如,-4 小时的-0400"或-04:00")或代表 UTC 分钟的数字(例如,DST 期间纽约的 240).

The older .zone() as a setter was deprecated in Moment.js 2.9.0. It accepted a string containing a timezone identifier (e.g., "-0400" or "-04:00" for -4 hours) or a number representing minutes behind UTC (e.g., 240 for New York during DST).

// always "2013-05-23 00:55"
moment(1369266934311).zone(-60).format('YYYY-MM-DD HH:mm')
moment(1369266934311).zone('+0100').format('YYYY-MM-DD HH:mm')

<小时>

要使用命名时区而不是数字偏移量,请包含 Moment Timezone 并使用 .tz() 改为:

// determines the correct offset for America/Phoenix at the given moment
// always "2013-05-22 16:55"
moment(1369266934311).tz('America/Phoenix').format('YYYY-MM-DD HH:mm')

相关文章