html5 date input field and valueAsDate timezone gotcha

Consider the following code

<html>
<body>
<div id=”o”></div>
<input id=”f” type=”date”/>
<div id=”o2″></div>
</body>
<script>
var d = new Date(2012,06,27);
o.innerHTML = d.toString();
f.valueAsDate = d;
o2.innerHTML = f.valueAsDate.toLocaleString();
</script>
</html>

The result might not be what you expected.  The resulting date, at least in the UK, is the 26th July 2012 not 27th July 2012 as you might expect.

The reason is that the date input field, valueAsDate property is a timezone-less date (that it, it works of the GMT time of the date you pass it).

When creating a date with new Date() or new Date(year, month, day) it is actually creating a date in local time, so for example, it might be 27th July 2012 00:00:00 BST (GMT+1).  So when this is assigned to valueAsDate of the input field, the date that the date field uses is 26th of July because the GMT time of my local time, is 23:00:00 on 26th July 2012.

To convert a local date to a form that is suitable for assigning to valueAsDate and preserve the local date, we must ensure that the GMT time is also for the same date, so can do the following:-

<html>
<body>
<div id=”o”></div>
<input id=”f” type=”date”/>
<div id=”o2″></div>
</body>
<script>
var d = new Date(2012,06,27);
o.innerHTML = d.toString();
f.valueAsDate = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 12);
o2.innerHTML = f.valueAsDate.toLocaleString();
</script>
</html>

What that does is, it ensure that date after conversion to GMT will still reference the original date.
Advertisements

About austinfrance

Technical Developer @ RedSky IT / Explorer Software
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s