格式化特定时区中的日期

问题描述:

我正在使用 Moment.js 来解析和格式化Web应用程序中的日期.作为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>

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

But how do I format a date in a specifc timezone?

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

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

Manto的答案 .utcOffset() 是首选方法.此函数使用UTC的实际偏移量,而不是反向偏移量(例如,夏令时期间,纽约为-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后的分钟的数字(例如,夏令时期间,纽约为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')


要使用命名时区而不是数字偏移量,请包含时刻时区并使用.tz()代替:


To work with named timezones instead of numeric offsets, include Moment Timezone and use .tz() instead:

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