Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

HTML5 Input type=date Formatting Issues


:P
On this page:

One of the nice features in HTML5 is the abililty to specify a specific input type for HTML text input boxes. There a host of very useful input types available including email, number, date, datetime, month, number, range, search, tel, time, url and week. For a more complete list you can check out the MDN reference. Date input types also support automatic validation which can be useful in some scenarios but maybe can get in the way at other times.

One of the more common input types, and one that can most benefit of a custom UI for selection is of course date input. Almost every application could use a decent date representation and HTML5's date input type seems to push into the right direction. It'd be nice if you could just say:

<form action="DateTest.html">
    <label for="FromDate">Enter a Date:</label>
<
input type="date" id="FromDate" name="FromDate" value="11/08/2012" class="date" /> <hr /> <input type="submit" id="btnSubmit" name="btnSubmit" value="Save Date" class="smallbutton" /> </form>

but if you'd expect to just work, you're likely to be pretty disappointed.

Problem #1: Browser Support

For starters there's browser support. Out of the major browsers only the latest versions of WebKit and Opera based browsers seem to support date input. Neither FireFox, nor any version of Internet Explorer (including the new touch enabled IE10 in Windows RT) support input type=date. Browser support is an issue, but it would be OK if it wasn't for problem #2.

Problem #2: Date Formatting

If you look at my date input from before:

<input type="date" id="FromDate" name="FromDate" 
       value="11/08/2012" class="date" />

You can see that my date is formatted in local date format (ie. en-us). Now when I run this sadly the form that comes up in Chrome (and also iOS mobile browsers) comes up like this:

EmptyDateBox

Chrome isn't recognizing my local date string. Instead it's expecting my date format to be provided in ISO 8601 format which is:

2012-11-08

So if I change the date input field to:

<input type="date" id="FromDate" name="FromDate" 
       value="2012-10-08" class="date" />

I correctly get the date field filled in:
DateWithISO

Also when I pick a date with the DatePicker the date value is also returned is also set to the ISO date format. Yet notice how the date is still formatted to the local date time format (ie. en-US format). So if I pick a new date:

DatePickingChrome

and then save, the value field is set back to:

2012-11-15

using the ISO format. The same is true for Opera and iOS browsers and I suspect any other WebKit style browser and their date pickers.

So to summarize input type=date:

  • Expects ISO 8601 format dates to display intial values
  • Sets selected date values to ISO 8601

Now what?

This would sort of make sense, if all browsers supported input type=date. It'd be easy because you could just format dates appropriately when you set the date value into the control by applying the appropriate culture formatting (ie. .ToString("yyyy-MM-dd") ). .NET is actually smart enough to pick up the date on the other end for modelbinding when ISO 8601 is used. For other environments this might be a bit more tricky.

input type=date is clearly the way to go forward. Date controls implemented in HTML are going the way of the dodo, given the intricacies of mobile platforms and scaling for both desktop and mobile. I've been using jQuery UI Datepicker for ages but once going to mobile, that's no longer an option as the control doesn't scale down well for mobile apps (at least not without major re-styling). It also makes a lot of sense for the browser to provide this functionality - creating a consistent date input experience across apps only makes sense, which is why I find it baffling that neither FireFox nor IE 10 deign it necessary to support date input natively.

The problem is that a large number of even the latest and greatest browsers don't support this. So now you're stuck with not knowing what date format you have to serve since neither the local format, nor the ISO format works in all cases.

Modernizr

It's possible to check for the availability of input types with Modernizr by checking:

Modernizr.inputtypes.date

for true or false. Unfortunately this is a client side thing, which means you'd have to delay formatting your date on the client using some sort of client library for date formatting like Moment.js rather than pushing a date into the UI from the server. This would work for a client heavy application that's using client side templates to render content, but not so well for a typical HTML server rendered app.

Compromise?

For my current app I just broke down and used the ISO format and so I'll live with the non-local date format.

<input type="date" id="ToDate" name="ToDate" 
       value="2012-11-08" class="date"/>

Here's what this looks like on Chrome:

ChromeInput

Here's what it looks like on my iPhone:

iphonedate

Both Chrome and the phone do this the way it should be. The iPhone date display and date picker in particular are very nice (better than anything on the desktop - that's for sure) and it demonstrates why we'd want this implemented in the browser to share this common UI for any application that provides date input. The iOS built-in date picker there certainly beats manually trying to edit the date using finger gymnastics.

Finally here's what the date looks like in FireFox which doesn't support date input types:

FireFoxISODateString

Certainly this is not the ideal date format, but it's clear enough I suppose. If users enter a date in local US format and that works as well (but won't work for other locales). It'll have to do.

Over time one can only hope that other browsers will finally decide to implement this functionality natively to provide a unique experience. Until then, incomplete solutions it is.

Related Posts

Posted in HTML5  HTML  

The Voices of Reason


 

Ventsi
November 09, 2012

# re: HTML5 Input type=date Formatting Issues

Hi, I had this problem a month ago, how to use webkit, iOS, Android support for date input field and to keep IE date select easy, for this I'm using Modernizr and jQueryUI
function hiddenDate(dateField) {
    var name = dateField.attr("name");
    var value = dateField.val();
    var hidden = $("<input></input>");
    hidden.prop("type", "hidden");
    hidden.prop("name", name);
    hidden.prop("id", "hid" + name);
    hidden.val(dateField.val());
    dateField.after(hidden);
    dateField.removeAttr("name");
 
    var dateValue = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
    if (dateValue)
        dateField.val(dateValue[3] + "/" + dateValue[2] + "/" + dateValue[1]);
    return hidden;
}
 
if (!window.Modernizr.inputtypes.date) {
    $("input[type='date']").each(function () {
        var $this = $(this);
        var hidden = hiddenDate($this);
        $this.datepicker(
                {
                    prevText: "",
                    nextText: "",
                    changeMonth: true,
                    changeYear: true,
                    altField: hidden,
                    altFormat: "yy-mm-dd"
                });
    });
}

I set my date fields with yyyy-mm-dd format and webkit is just ok, for other browsers I create a hidden field which contains date in format yyyy-mm-dd and jQueryUI date selector uses localized format.

Ted Roche
November 09, 2012

# re: HTML5 Input type=date Formatting Issues

I agree: ANSI/ISO format YYYY-MM-DD is intended to be non-ambiguous: 11-08-12 is November 8, 11 August or...? But it is a PITA because no one thinks that way.

I use type=date combined with Modernizr and jQuery datepicker: native support is displayed if available (and is supposed to display the textbox value per the OS settings), jQuery date picker understands values YYYY-MM-DD and shows the correct highlighted value on its popup calendar. Display in the text box with follow the jQuery datepicker dateFormat property, so if you're doing i18n that needs setting programmatically.

Consider, too, using the placeholder and title options to provide coaching on proper data entry. It does violate the "Don't Make Me Think" principle, though.

For those without native support and without Javascript enabled... That's a call I work out with the paying client. My preference would be a generic NOSCRIPT with a display that Javascript is required for proper site operation, placed in the template, but for the client _willing_to_pay_for_it use of NOSCRIPT to load the page with prompts is usually the best you can offer. It's been my experience that offering IE6 and non-JS support at a higher cost tends to discourage that work ;)

This is one of those frontiers where progressive enhancement and graceful degradation is challenging!

Rick Strahl
November 12, 2012

# re: HTML5 Input type=date Formatting Issues

@Ted - Yes Modernizr checks work, but there are problems with that too. First you need to decide up front what format to render from the server, unless you want to do post processing on the client (which sucks especially if you have clean views - applies even for client templates for that matter). The other issue that bugs me about this is that jQuery DatePicker falls down pretty hard on mobile unless custom styled and even then it looks pretty out of place if you're running ViewPort scale=1.

Richard
July 12, 2013

# re: HTML5 Input type=date Formatting Issues

> First you need to decide up front what format to render from the server ...

Are you not doing that already? Or are you serving up all dates on an international site with a US format?

And even if you change the format based on the user's "accept-language" header, that doesn't account for browsers like Chrome which default to "en-US" regardless of the computer's locale.

I'd much rather see dates in the unambiguous ISO format, so that I don't have to play another round of "guess the order of the date parts"!

Rick Strahl
July 12, 2013

# re: HTML5 Input type=date Formatting Issues

@Richard - For display purposes I tend to use MMM dd, yyyy format for dates because it's easier to parse and non-ambiguous. For input though it depends on the app. In some apps we sniff the browser's locale and use that for formatting, in other apps serve US format only.

I'm also leaning towards always using the ISO format because it too is pretty clear what the format is, but I still don't really like the way that looks. This is why I say that it sucks that browsers don't handle this for you.

Ideally what I want is:
* Have the date format set in the value be ISO format
* Have the display format in the browser locale format
* Have the editing experience a browser provided date picker

One can dream huh? This should address all use cases realistically. If you don't want to have the browser step in at all (ie. we take over rendering using a JavaScript/HTML plugin) then we can simply use type="text" instead of type="date".

It's really not that complicated.

FWIW, I checked out a Windows Phone IE browser today and first thing I noticed is that it doesn't support date input in any way in the browser. No date control, not even special date related characters on the display keyboard - terrible user experience there.

Richard
July 12, 2013

# re: HTML5 Input type=date Formatting Issues

Yeah, one day we might get there! For the moment, the support is appalling:
http://caniuse.com/#feat=input-datetime

JT
October 27, 2013

# re: HTML5 Input type=date Formatting Issues

I've ended up making some php functions to do a browser detect and reformat the date string from my sql result based on where the browser is iphone webkit or something else.

///
function fix_sql_date($date){
$browser = browser_type();
if ($browser == "iPhone"){
return $date; //returns as yyyy/mm/dd (same as mysql date)
}
if ($browser == "webkit"){
return $date; //returns as yyyy/mm/dd (same as mysql date)
}
$date = explode('-',$date);
return $date[2].'/'.$date[1].'/'.$date[0]; //reformat string to dd/mm/yyyy

}
//////////
Function browser_type (){
$iPod = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
$iPhone = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$iPad = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
$webkit = stripos($_SERVER['HTTP_USER_AGENT'],"webkit");
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android");
$webOS = stripos($_SERVER['HTTP_USER_AGENT'],"webOS");

//do something with this information
if( $iPod || $iPhone ){
//browser reported as an iPhone/iPod touch -- do something here
return "iPhone";
}else if($iPad){
//browser reported as an iPad -- do something here
return $iPad;
}else if($webkit){
//browser reported as an webkit -- do something here
return "webkit";
}else if($Android){
//browser reported as an Android device -- do something here
return $Android;
}else if($webOS){
//browser reported as a webOS device -- do something here
return $webOS;
}else {
return $_SERVER['HTTP_USER_AGENT'];
}
}

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024