Fragmented Thought

Displaying date input values using javascript

By

Published:

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

A minor annoyance you might not consider at first working with HTML 5 date type inputs:

The date display is what the user is thinking. Say: Oct 31st, 2008 translating to their locale. For me, that's 10/31/2008.

The input's value will be: "2008-10-31" - Makes perfect sense.

The input's valueAsDate will be: "2008-10-29 18:00:00 -0600 CST" - Errr... What?

It makes sense actually. The date is being measured as against your UTC offset so it's localized. That's normally transparent, unless you were to need to then output that date back to the user via javascript. Then it gets interesting. The date can slip to the previous day, and you're showing their appointment 'accurately' but completely wrong. Remember, the user is not considering time, you'll have to remove it from the equation to match their expectations:

// The date input stores the time in local timezone format // To output the string 'as it appears' rather than shifted by local // We have to shift the date by the offset before displaying it var displayDate = field.valueAsDate; displayDate.setMinutes(displayDate.getTimezoneOffset()); return displayDate.toLocaleDateString();