Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 640
Giddswindle Avatar asked Dec 11 '22 04:12

Giddswindle


1 Answers

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();
like image 117
Matt Johnson-Pint Avatar answered Jan 11 '23 22:01

Matt Johnson-Pint