javascript HTML 输入类型 datetime-local 设置错误的时区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24703698/
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
HTML Input type datetime-local setting the wrong time-zone
提问by Giddswindle
I've created an app that takes in HTML inputs and goes through JavaScript to create an event on a native calendar events. It takes the time from the <input type="datetime-local">
, and it's putting in a different time because it's picking a different time zone. If I enter 1 o'clock PM as a time it will return 8 o'clock AM.
我创建了一个应用程序,它接受 HTML 输入并通过 JavaScript 在本机日历事件上创建一个事件。它从 中花费时间<input type="datetime-local">
,并且因为它选择了不同的时区,所以它放入了不同的时间。如果我输入 1 点钟作为时间,它将返回上午 8 点钟。
<input type="datetime-local" id="startDate" name="startDate">
And the JavaScript:
和 JavaScript:
var startDate = new Date($("#startDate").val());
Any help would be awesome. I can post more code if needed.
任何帮助都是极好的。如果需要,我可以发布更多代码。
回答by Matt Johnson-Pint
The HTML5 datetime-local
input type will give you a stringvalue back, which contains the date and time in ISO8601 format, with minute precision, and without any time zone offset.
HTML5datetime-local
输入类型将返回一个字符串值,其中包含 ISO8601 格式的日期和时间,具有分钟精度,并且没有任何时区偏移。
For example: 2014-07-12T01:00
例如: 2014-07-12T01:00
The JavaScript
date object is notoriously inconsistent when it comes to parsing dates from strings. In most implementations, when you provide a string like this, it erroneously assumes the value is in UTC. Therefore, the Date
object you get back will be adjusted by the time zone offset from your local computer.
在JavaScript
从字符串解析日期时,日期对象是出了名的不一致。在大多数实现中,当您提供这样的字符串时,它错误地假定该值是 UTC。因此,Date
您返回的对象将根据与本地计算机的时区偏移进行调整。
There are two approaches to work around the problem:
有两种方法可以解决此问题:
Option 1
选项1
Manipulate the string to a format that will likely be interpreted as local time by the Date
object's parser. Specifically, replace the dashes (-
) with forward slashes (/
) and replace the T
with a space.
将字符串处理为可能被Date
对象的解析器解释为本地时间的格式。具体来说,将破折号 ( -
)替换为正斜杠 ( /
),并将 替换T
为空格。
var s = $("#startDate").val();
var startDate = new Date(s.replace(/-/g,'/').replace('T',' '));
Option 2
选项 2
Use a library with more capable date parsing abilities. There are several available. One of the most popular is moment.js.
使用具有更强大的日期解析能力的库。有几种可用。最流行的一种是moment.js。
Moment.js has lots of options, but it just so happens that the default behavior is exactly what you need. So you can just pass the string to the moment constructor without any parameters.
Moment.js 有很多选项,但碰巧默认行为正是您所需要的。因此,您可以将字符串传递给不带任何参数的 moment 构造函数。
var s = $("#startDate").val();
var startDate = moment(s).toDate();