I'm using Bootstrap datepicker. The answer is probably obvious, but I can't figure out how to get the selected date as a string in the specified format. I used:
<div id="myDate" data-date-format="yyyy-mm-dd">
<input type="text">
</div>
And in my javascript:
var value = $("#myDate").datepicker("getDate");
But it returns a date, not a string in yyyy-mm-dd format.
In order to set the date format, we only need to add format of one argument and then we will add our required format, which is shown in the following example: Example 1: In this example, we are going to use dd-mm-yyyy format.
An input element that is to be updated with the selected date from the datepicker. Use the altFormat option to change the format of the date within this field.
var year = 2014; var month = 5; var day = 10; var realDate = new Date(year, month - 1, day); // months are 0-based! $('#MainContent_txtDataConsegna'). datepicker({ dateFormat: 'dd/mm/yyyy' }); // format to show $('#MainContent_txtDataConsegna'). datepicker('setDate', realDate);
The data-date-format="mm/dd/yyyy"
needs to be set on the input:
<input type="text" data-date-format="MM/DD/YYYY">
Your jQuery should also be changed to:
var value = $("#myDate input").datepicker("getDate");
Or you can just keep things simple with no wrapping div
and with this your original jQuery would work fine and you wouldn't have to specify input
:
<input type="text" id="myDate" data-date-format="YYYY-MM-DD">
Suggestion
I would recommend creating a class to format the datepicker. So that you can then add the .datepicker
class to any input field and it would work without having to specify another variable.
Fiddle
Here is working code with alert of date http://jsfiddle.net/doitlikejustin/HFuDg/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With