I am using the UI DatePicker from jQuery UI as the stand alone picker. I have this code:
<div id="datepicker"></div>
And the following JS:
$('#datepicker').datepicker();
When I try to return the value with this code:
var date = $('#datepicker').datepicker('getDate');
I am returned this:
Tue Aug 25 2009 00:00:00 GMT+0100 (BST)
Which is totally the wrong format. Is there a way I can get it returned in the format DD-MM-YYYY
?
The
getDate
method of datepicker returns a date type, not a string.You need to format the returned value to a string using your date format. Use datepicker's
formatDate
function:The full list of format specifiers is available here.
If you need the date in yy-mm-dd format,you can use this:-
You can find all the supported format https://jqueryui.com/datepicker/#date-formats
I was in need of 06,Dec 2015,I did this:-
You can add and try this way:
HTML file:
JavaScript file:
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 types1-1-1
. The datepicker will convert this toJan 01, 2001
internally but callingval()
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:
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.I use this:
Which returns a date of format like "
20120118
" forJan 18, 2012
.This works too: