停止 javascript 日期函数更改时区偏移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17751698/
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 09:28:49  来源:igfitidea点击:

Stop javascript Date function from changing timezone offset

javascriptdatedatetimetimezone

提问by user2434674

So I have iso date time that need to be converted from a string to date object. How do I keep date from converting it to local browser timezone.

所以我有iso日期时间需要从字符串转换为日期对象。如何避免将日期转换为本地浏览器时区。

new Date('2013-07-18T17:00:00-05:00')
Thu Jul 18 2013 18:00:00 GMT-0400 (EDT)

I want to get

我想得到

Thu Jul 18 2013 17:00:00 GMT-0500 (XX)

2013 年 7 月 18 日星期四 17:00:00 GMT-0500 (XX)

回答by andreisrob

While MomentJS is a great library, it may not provide a solution for every use case. For example, my server provides dates in UTC, and when the time portion of the date is not saved in the db (because it's irrelevant), the client receives a string that has a default time of all zeros - midnight - and ends with an offset of +0000. The browser then automatically adjusts for my local time zone and pulls the time back by a few hours, resulting in the previous day.

虽然 MomentJS 是一个很棒的库,但它可能无法为每个用例提供解决方案。例如,我的服务器以 UTC 提供日期,并且当日期的时间部分未保存在 db 中时(因为它无关紧要),客户端会收到一个字符串,该字符串的默认时间全为零 - 午夜 - 并以的偏移量+0000。然后浏览器会根据我的本地时区自动调整并将时间拉回几个小时,结果是前一天。

This is true with MomentJs as well.

MomentJs 也是如此。

One solution is to slice off the time portion of the string, and then use MomentJS as described in the other answers.

一种解决方案是切掉字符串的时间部分,然后按照其他答案中的描述使用 MomentJS。

But what happens if MomentJS is not a viable option, i.e. I already have many places that use a JS Date and don't want to update so many lines of code? The question is how to stop the browser from converting dates based on local time zone in the first place. And the answer is, when the date is in ISO format, you cannot.

但是如果 MomentJS 不是一个可行的选择会发生什么,即我已经有很多地方使用了 JS Date 并且不想更新这么多行代码?问题是首先如何阻止浏览器根据本地时区转换日期。答案是,当日期为 ISO 格式时,您不能。

However, there is no rule that says the string you pass to JavaScript's Date constructor must be in ISO format. If you simply replace the -that separates the year, month, and day with a /, your browser will notperform any conversion.

但是,并没有规定您传递给 JavaScript 的 Date 构造函数的字符串必须采用 ISO 格式。如果您简单地将-分隔年、月和日的 替换为/,您的浏览器将不会执行任何转换。

In my case, I simply changed the format of the Dates server-side, and the problem was solved without having to update all the client-side JS dates with MomentJS.

就我而言,我只是简单地更改了服务器端日期的格式,问题就解决了,而无需使用 MomentJS 更新所有客户端 JS 日期。

Note that the MDN docs for JavaScript's Date class warn about unpredictable browser-behavior when parsing a string to create a Date instance.

请注意,JavaScript 的 Date 类的 MDN 文档在解析字符串以创建 Date 实例时警告不可预测的浏览器行为。

回答by Xowap

You cannot change this behavior of Javascript because it is the only simple way for Javascript to work. What happens is simply that Javascript looks at the time shift, computes the matching timestamp, and then asks the OS for the representation of this timestamp in the local time zone. What is key to understand here is that -05:00is not an indication of time zone but simply a shift from UTC.

您无法更改 Javascript 的这种行为,因为它是 Javascript 工作的唯一简单方式。发生的事情很简单,Javascript 查看时间偏移,计算匹配的时间戳,然后要求操作系统在本地时区中表示该时间戳。这里要理解的关键是这-05:00不是时区的指示,而只是与 UTC 的转换。

Time zones are complex beasts that are just arbitrary political decisions. The OS provides a service to display time in the local time zone, but not in other time zones. To do that you have to take in account things like DST that are pretty much a hell.

时区是复杂的野兽,只是任意的决定。操作系统提供了一项服务以显示本地时区的时间,但不显示其他时区的时间。为此,您必须考虑诸如 DST 之类的东西,这几乎是地狱。

As always with time management, the only decent way to tackle this problem is to use a dedicated library. In Javascript, you'll find Moment.jsand Moment.Timezone.jsvery helpful.

与时间管理一样,解决这个问题的唯一体面方法是使用专用库。在 Javascript 中,您会发现Moment.jsMoment.Timezone.js非常有用。

Example http://codepen.io/Xowap/pen/XKpKZb?editors=0010

示例http://codepen.io/Xowap/pen/XKpKZb?editors=0010

document.write(moment('2013-07-18T17:00:00-05:00').tz('America/New_York').format('LLL'));

As a bonus, you get a ton of formatting/parsing features from Moment.js.

作为奖励,您可以从 Moment.js 获得大量格式化/解析功能。

Please also note that as long as you use the ISO 8601, your date can be pinpointed to a precise moment, and thus be displayed in any timezone of your liking. In other words, JS "converting" your date doesn't matter.

另请注意,只要您使用 ISO 8601,您的日期就可以精确定位到一个精确的时刻,从而显示在您喜欢的任何时区。换句话说,JS“转换”你的日期并不重要。

回答by penguin

You can use a library such as Moment.jsto do this.

您可以使用诸如Moment.js 之类的库来执行此操作。

See the String + Format parsing.

请参阅字符串 + 格式解析

http://momentjs.com/docs/#/parsing/string-format/

http://momentjs.com/docs/#/parsing/string-format/

The following should parse your date you provided, but you may need to modify it for your needs.

以下内容应解析您提供的日期,但您可能需要根据需要对其进行修改。

var dateString = "2013-07-18T17:00:00-05:00";

var dateObject = moment(dateString, "YYYY-MM-DDTHH:mm:ssZ").toDate();

Alternatively, see Moment's String parser, which looks like it is in the format you provided, with the exception of a space between the seconds of the time and the time zone.

或者,请参阅 Moment 的字符串解析器,它看起来像您提供的格式,但时间的秒数和时区之间有一个空格。

http://momentjs.com/docs/#/parsing/string/

http://momentjs.com/docs/#/parsing/string/

回答by Paul

Wonder if this would help:

想知道这是否有帮助:

function goAheadMakeMyDate(s){
  var d = new Date(s);
  // override Date.toString()
  d.toString = function(){ return ''+s; };
  return d;
}

var example = goAheadMakeMyDate("Fri 19 July 2013 12:00:00 GMT");

example.toString() // returns string actually used to construct the date
'Fri 19 July 2013 12:00:00 GMT'

example.toLocaleString()
'Fri Jul 19 2013 08:00:00 GMT-0400 (EDT)'

1*example // gives seconds since epoch
1374235200000

With your input:

根据您的输入:

example = goAheadMakeMyDate('2013-07-18T17:00:00-05:00')
{ Thu, 18 Jul 2013 22:00:00 GMT toString: [Function] }
> example.toString()
'2013-07-18T17:00:00-05:00'
> example.toLocaleString() // I live in GMT-4
'Thu Jul 18 2013 18:00:00 GMT-0400 (EDT)'
> 1*example  // convert to integer date
1374184800000

However, if you start modifying this date, the toString will notchange and will bite you.

但是,如果您开始修改此日期,则 toString不会更改并且会咬您。

回答by benvc

This is an old question that recently got linked in an answer to a newer question, but none of the existing answers seem to fully address the original question.

这是一个老问题,最近在一个新问题的答案中链接到了这个问题,但现有的答案似乎都没有完全解决原始问题。

In many cases the easiest way to format and display a datetime string in the time zone that it is received, is not to convert the string to a Dateobject at all. Instead, just parse the datetime string and recombine the parts into the desired format. For example, if you can live without the day of the week in the output requested in the question, you could do something like the following to handle the requested input and output format (including the day of the week adds enough complexity that it might be worth using a library at that point). Of course, this approach requires modification based on the format of the datetime strings you are receiving on the client side.

在许多情况下,在接收到的时区格式化和显示日期时间字符串的最简单方法是根本不将字符串转换为Date对象。相反,只需解析日期时间字符串并将这些部分重新组合成所需的格式。例如,如果您可以在问题中请求的输出中没有星期几,您可以执行以下操作来处理请求的输入和输出格式(包括星期几增加了足够的复杂性,它可能是值得在那时使用图书馆)。当然,这种方法需要根据您在客户端收到的日期时间字符串的格式进行修改。

const months = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'};

const format = (datetime) => {
  let [date, time] = datetime.split('T');
  let [y, m, d] = date.match(/\d+/g);
  let [t, tz] = time.split(/(?=[+-])/);
  return `${months[parseInt(m)]} ${d} ${y} ${t} GMT${tz}`;
}

let dt = format('2013-07-18T17:00:00-05:00');
console.log(dt);
// Jul 18 2013 17:00:00 GMT-05:00

There are JavaScript and other library methods that will allow you to convert your datetime string to a Dateinstance and then display it in a specific time zone if you are consistently receiving datetime strings from one or a few specific time zones that are easily identified on the client side. Following are a couple of examples.

JavaScript 和其他库方法允许您将日期时间字符串转换为Date实例,然后在特定时区中显示它,如果您一直从客户端上很容易识别的一个或几个特定时区接收日期时间字符串边。以下是几个例子。

toLocaleStringenables you to display a date in a specific time zone but the optionsparameters required to set the time zone are not supported across all browsers (as of the date of this answer). For example (note that parsing of date strings with the Dateconstructor is still discouraged, but most modern browsers will handle an ISO 8601 format string like the one below):

toLocaleString使您能够显示特定时区中的日期,但options并非所有浏览器都支持设置时区所需的参数(截至本答案的日期)。例如(请注意,Date仍然不鼓励使用构造函数解析日期字符串,但大多数现代浏览器将处理 ISO 8601 格式字符串,如下所示):

const dt = new Date('2013-07-18T17:00:00-05:00');
const ny = dt.toLocaleString('en-US', { timeZone: 'America/New_York' });

console.log(`Local: ${dt}`);
console.log(`New York: ${ny}`);

You could also use Moment.jswith Moment Timezoneto display a date in a specific time zone. For example:

您还可以将Moment.jsMoment Timezone 结合使用以显示特定时区中的日期。例如:

const ny = moment('2013-07-18T17:00:00-05:00').tz('America/New_York').format()

console.log(`New York: ${ny}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>

It is important to note the following when working with datetime strings and time zones in JavaScript. The JavaScript Dateconstructor DOES NOT change the time zone offset. When you create a date from a string using ISO 8601 format as in the question example, Datedoes the following:

在 JavaScript 中使用日期时间字符串和时区时,请务必注意以下几点。JavaScriptDate构造函数不会更改时区偏移量。当您按照问题示例使用 ISO 8601 格式从字符串创建日期时,请Date执行以下操作:

Creates a JavaScript Date instance that represents a single moment in time. Date objects use a Unix Time Stamp, an integer value that is the number of milliseconds since 1 January 1970 UTC.

创建一个表示单个时刻的 JavaScript Date 实例。日期对象使用 Unix 时间戳,这是一个整数值,它是自 1970 年 1 月 1 日UTC 以来的毫秒数。

In other words, JavaScript Dateinstances do not store (or change) time zone offsets. The reason you often see output from a JavaScript Datein your local time zone is that toStringis the default method called when you log a Dateinstance to the console (or use various other approaches to output your date). In most browser implementations, this method relies on the browser's local time zone to convert the number of milliseconds since 1 January 1970 UTC into a string representation of the date.

换句话说,JavaScriptDate实例不存储(或更改)时区偏移量。您经常Date在本地时区看到 JavaScript 输出的原因是,这toString是将Date实例记录到控制台时调用的默认方法(或使用各种其他方法输出日期)。在大多数浏览器实现中,此方法依赖于浏览器的本地时区将自 UTC 1970 年 1 月 1 日以来的毫秒数转换为日期的字符串表示形式。