javascript 在特定时区格式化日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15347589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:29:00  来源:igfitidea点击:

Format date in a specific timezone

javascripttimezonemomentjs

提问by quietmint

I'm using Moment.jsto 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).

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

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

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

// 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?

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

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

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

回答by quietmint

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:

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

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

The older .zone()as a setterwas deprecatedin 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 behindUTC (e.g., 240 for New York during DST).

在 Moment.js 2.9.0中不推荐使用较旧.zone()的 setter。它接受含有时区标识符的字符串(例如,“-0400”或“-04:00”为-4小时),或者表示分钟数后面UTC(例如,240为纽约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')


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

要使用命名时区而不是数字偏移量,请包括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')

回答by Philip Nuzhnyy

Use moment-timezone

使用时刻时区

moment(date).tz('Europe/Berlin').format(format)

Before being able to access a particular timezone, you will need to load it like so (or using alternative methods described here)

在能够访问特定时区之前,您需要像这样加载它(或使用此处描述的替代方法)

moment.tz.add('Europe/Berlin|CET CEST CEMT|-10 -20 -30')

回答by Nicola Pedretti

A couple of answers already mention that moment-timezone is the way to go with named timezone. I just want to clarify something about this library that was pretty confusing to me. There is a difference between these two statements:

几个答案已经提到时刻时区是命名时区的方式。我只是想澄清一些让我感到困惑的关于这个库的事情。这两种说法有区别:

moment.tz(date, format, timezone)

moment(date, format).tz(timezone)


Assuming that a timezone is not specified in the date passed in:

假设传入的日期中未指定时区:

The first code takes in the date and assumes the timezone is the one passed in. The second one will take date, assume the timezone from the browser and then change the time and timezone according to the timezone passed in.

第一个代码接收日期并假设时区是传入的时区。第二个代码将接收日期,假设浏览器中的时区,然后根据传入的时区更改时间和时区。

Example:

例子:

moment.tz('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss', 'UTC').format() // "2018-07-17T19:00:00Z"

moment('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss').tz('UTC').format() // "2018-07-18T00:00:00Z"

My timezone is +5 from utc. So in the first case it does not change and it sets the date and time to have utc timezone.

我的时区是 UTC +5。因此,在第一种情况下,它不会更改,而是将日期和时间设置为具有 UTC 时区。

In the second case, it assumes the date passed in is in -5, then turns it into UTC, and that's why it spits out the date "2018-07-18T00:00:00Z"

在第二种情况下,它假设传入的日期是 -5,然后将其转换为 UTC,这就是为什么它会吐出日期“2018-07-18T00:00:00Z”

NOTE: The format parameter is really important. If omitted moment might fall back to the Date class which can unpredictable behaviors

注意:格式参数非常重要。如果省略 moment 可能会回退到 Date 类,这会导致不可预测的行为



Assuming the timezone is specified in the date passed in:

假设时区在传入的日期中指定:

In this case they both behave equally

在这种情况下,它们的行为相同



Even though now I understand why it works that way, I thought this was a pretty confusing feature and worth explaining.

尽管现在我明白为什么它会这样工作,但我认为这是一个非常令人困惑的功能,值得解释。

回答by Manto

.zone() has been deprecated, and you should use utcOffset instead:

.zone() 已被弃用,您应该使用 utcOffset 代替:

// for a timezone that is +7 UTC hours
moment(1369266934311).utcOffset(420).format('YYYY-MM-DD HH:mm')

回答by facundofarias

I was having the same issue with Moment.js. I've installed moment-timezone, but the issue wasn't resolved. Then, I did just what here it's exposed, set the timezone and it works like a charm:

我在 Moment.js 上遇到了同样的问题。我已经安装了moment-timezone,但问题没有解决。然后,我做了这里暴露的事情,设置时区,它就像一个魅力:

moment(new Date({your_date})).zone("+08:00")

Thanks a lot!

非常感谢!

回答by Bard Rotzer

Just came acreoss this, and since I had the same issue, I'd just post the results I came up with

刚刚出现这个问题,因为我遇到了同样的问题,所以我只是发布了我想出的结果

when parsing, you could update the offset (ie I am parsing a data (1.1.2014) and I only want the date, 1st Jan 2014. On GMT+1 I'd get 31.12.2013. So I offset the value first.

解析时,您可以更新偏移量(即我正在解析数据(1.1.2014),我只想要日期,2014 年 1 月 1 日。在 GMT+1 上,我会得到 31.12.2013。所以我首先偏移了值。

moment(moment.utc('1.1.2014').format());

Well, came in handy for me to support across timezones

好吧,这对我支持跨时区很有用

B

回答by K.Karthik

You can Try this ,

你可以试试这个,

Here you can get the date based on the Client Timezone (Browser).

在这里您可以根据客户端时区(浏览器)获取日期。

moment(new Date().getTime()).zone(new Date().toString().match(/([-\+][0-9]+)\s/)[1]).format('YYYY-MM-DD HH:mm:ss')

The regex basically gets you the offset value.

正则表达式基本上为您提供偏移值。

Cheers!!

干杯!!