我创建了一个应用程序,它接受 HTML 输入并通过 JavaScript 在本机日历事件上创建一个事件.它从 <input type="datetime-local">
中花费时间,并且由于选择了不同的时区,因此它输入了不同的时间.如果我输入 1 o'clock PM 作为时间,它将返回 8 o'clock AM.
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.
例如:2014-07-12T01:00
JavaScript
日期对象在从字符串中解析日期时是出了名的不一致.在大多数实现中,当您提供这样的字符串时,它会错误地假定该值是 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.
Moment.js 有很多选项,但碰巧默认行为正是您所需要的.因此,您可以将字符串传递给 moment 构造函数而无需任何参数.
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 设置错误的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!