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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With