HTML输入类型datetime-local设置错误的时区 [英] HTML Input type datetime-local setting the wrong time-zone

查看:923
本文介绍了HTML输入类型datetime-local设置错误的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个应用程序,它接收HTML输入,并通过JavaScript在本地日历事件上创建一个事件。它需要时间从< input type =datetime-local> ,并且它在不同的时间,因为它选择不同的时区。如果我进入下午1点钟,那么AM会在8点钟之后返回。

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.

<input type="datetime-local" id="startDate" name="startDate">

而JavaScript:

And the JavaScript:

var startDate = new Date($("#startDate").val());

任何帮助都会很棒。如果需要,我可以发布更多的代码。

Any help would be awesome. I can post more code if needed.

推荐答案

HTML5 datetime-local 输入类型会给你一个 string 返回,其中包含ISO8601格式的日期和时间,分辨率精确,没有任何时区偏移。

The HTML5 datetime-local input type will give you a string value back, which contains the date and time in ISO8601 format, with minute precision, and without any time zone offset.

例如: code> 2014-07-12T01:00

For example: 2014-07-12T01:00

JavaScript date当从字符串中解析日期时,对象是非常不一致的。在大多数实现中,当您提供这样的字符串时,它错误地假定该值为UTC。因此,您返回的 Date 对象将根据本地计算机的时区偏移量进行调整。

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.

是解决问题的两种方法:

There are two approaches to work around the problem:

选项1

字符串到一个可能被 Date 对象的解析器解释为本地时间的格式。具体来说,用正斜杠( / )替换破折号( - ),并替换 T

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.

var s = $("#startDate").val();
var startDate = new Date(s.replace(/-/g,'/').replace('T',' '));

选项2

使用具有更强大的日期解析功能的库。有几个可用。最受欢迎的是 moment.js

Use a library with more capable date parsing abilities. There are several available. One of the most popular is moment.js.

时刻。 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.

var s = $("#startDate").val();
var startDate = moment(s).toDate();

这篇关于HTML输入类型datetime-local设置错误的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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