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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…