GSaunders
GSaunders

Reputation: 548

Input type date format and datepicker issues

I'm working with HTML5 elements input attributes and only Chrome, iOS safari and Opera seem to support it at this time. So I have created a jQuery UI datepicker fallback for browsers that do not support it yet, but there are a few issues I'm running into and haven't been able to find any answers for.

  1. If I put in the date format that the datepickers requires and then pick a new date, there is an extra yyyy
  2. I think the yyyy-mm-dd format is ridiculous and would like it be displayed mm/dd/yyyy like chrome does even though the value is still yyyy-mm-dd. Is there a way to do this with datepicker or a better solution?

Example

JS

if (!Modernizr.inputtypes.date) {
  $('input[type=date]').datepicker({
    dateFormat: 'yyyy-mm-dd' // HTML 5 
  });
}

HTML

<input type="date" value="2014-01-07" />

Please look in firefox to view the datepicker fallback and chrome to view the input type date.

Upvotes: 4

Views: 22331

Answers (2)

Tim
Tim

Reputation: 1317

Here is the solution I came to to use only one input (no need of a hidden input).

$('input[type="date"], input[type="datetime"]').datepicker({
    dateFormat: 'yy-mm-dd', 
    altFormat: 'dd.mm.yy', 
    altField: $(this)
});

In the altFormat set the format you want to show your user, altField is your date field, dateFormat is the HTML5 date format.

Upvotes: 2

adeneo
adeneo

Reputation: 318212

Firsly, jQuery's datepicker does it a little differently, a full year is just yy so doing yyyy gets you the full year twice.

Here's a list of the date formats -> http://api.jqueryui.com/datepicker/#utility-formatDate

Note that y is a two-digit year, and yy is a four digit year.

To show the datepicker with one format, and submit a different format, you'd use the altField option and another input that holds the alternative value.
That's the input that you'll submit, while you're showing the user the original input.

To set that up for the native datepicker as well, you'd do something like

<input type="date" id="date" />
<input type="hidden" id="alternate" />

and

if (!Modernizr.inputtypes.date) {
    $( "#date" ).datepicker({
        dateFormat : 'mm/dd/yy',
        altFormat  : "yy-mm-dd",
        altField   : '#alternate'
    });
} else {
    $('#date').on('change', function() {
        $('#alternate').val(this.value);
    });
}

FIDDLE

Upvotes: 4

Related Questions