Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 views
in Technique[技术] by (71.8m points)

javascript - HTML Input type datetime-local setting the wrong time-zone

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">

And the JavaScript:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

For example: 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.

There are two approaches to work around the problem:

Option 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.

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

Option 2

Use a library with more capable date parsing abilities. There are several available. One of the most popular is 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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...