I am using the UI DatePicker from jQuery UI as the stand alone picker. I have this code:
And the
If you setup a datepicker on an input[type="text"]
element you may not get a consistently formatted date, particularly when the user doesn't follow the date format for data entry.
For example, when you set the dateFormat as dd-mm-yy
and the user types 1-1-1
. The datepicker will convert this to Jan 01, 2001
internally but calling val()
on the datepicker object will return the string "1-1-1"
-- exactly what is in the text field.
This implies you should either be validating the user input to ensure the date entered is in the format you expect or not allowing the user to enter dates freeform (preferring instead the calendar picker). Even so it is possible to force the datepicker code to give you a string formatted like you expect:
var picker = $('#datepicker');
picker.datepicker({ dateFormat: 'dd-mm-yy' });
picker.val( '1-1-1' ); // simulate user input
alert( picker.val() ); // "1-1-1"
var d = picker.datepicker( 'getDate' );
var f = picker.datepicker( 'option', 'dateFormat' );
var v = $.datepicker.formatDate( f, d );
alert( v ); // "01-01-2001"
Be aware however that while the datepicker's getDate()
method will return a date, it can only do so much with user input that doesn't exactly match the date format. This means in the absence of validation it is possible to get a date back that is different from what the user expects. Caveat emptor.