Wednesday, February 13, 2013

HTML5 Date Pickers and JavaScript Date Objects

HTML5 date picker elements have a lot of potential. After all, there are tons of apps out there that need a control for choosing a date. The number of browsers that support them is gradually growing, but not as quickly as you'd expect. Here's what it looks like in your browser -- it might just be a text box if your browser doesn't yet support date pickers:

Because of the lack of support in some browsers and the simple implementation in others, many developers still end up going with jQuery UI to render their date pickers.

If you choose to go with the native HTML5 control, you might notice a problem when creating a JavaScript Date object from the value in your date picker control. Here's some code that simply puts the value from the date picker into a JavaScript Date object. You can try it out live with the form below the code.

(date will dump here)

Depending on where you live, it's possible that the date on the right doesn't match the date on the control. And if it does, the time stamp on it is likely not midnight.

So what's going on, here? Is this a bug?

According to the specifications, date picker controls will have a value in RFC 3339 format, which is a profile of ISO 8601. When you new up a JavaScript Date in that format, you'll get a date that accounts for your timezone.

In other words, new Date("2013-02-14") creates a new Date object that refers to Valentine's Day at midnight in GMT – not in your time zone (unless your timezone is GMT). Depending on your app, you might or might not want that. It's entirely possible that you want Valentine's Day at midnight in your local time zone, or that you just want a date, with no respect for time zone.

A Solution

Interestingly, it seems that if you replace the hyphens with slashes, you get a date that does not compensate for your time zone. Notice the highlighted line below where I do the replacement.

(date will dump here)

So, when converting your date picker values to JavaScript Date objects, you might need to do that hyphen-to-slash replacement on the values first, in order to get a Date object that represents the chosen date at midnight GMT. It all depends on what you want.

No comments:

Post a Comment

Profile Picture
Dave Leeds
My Hobbies:
  • Programming
  • Cartooning
  • Music Writing
Full Profile