Moment.js:在特定时区中格式化日期 [英] Moment.js: Format date in a specific timezone

查看:1423
本文介绍了Moment.js:在特定时区中格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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
moment('3/11/2012 13:00').utc().format("MM/DD HH:mm")

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

但如何在特定时区格式化日期 ?无论浏览器的当前时间如何,我都希望获得一致的结果,但我不希望以UTC格式显示日期。

But how do I format a date in a specifc timezone? I want consistent results regardless of the browser's current time, but I don't want to display dates in UTC.

推荐答案

如指出的那样在 Manto的回答中, .utcOffset() 是从时刻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()作为setter 已弃用 .js 2.9.0。它接受包含时区标识符的字符串(例如,-0400或-04:00-4小时)或代表背后 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')

这篇关于Moment.js:在特定时区中格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆