問題描述
我正在使用 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')
這篇關于在特定時區格式化日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!