Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap datepicker -- how to get date as a string in the right format?

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.

like image 518
ccleve Avatar asked Aug 12 '13 20:08

ccleve


People also ask

How do I change the datepicker format in bootstrap?

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.

How do I change date format in datepicker?

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.

How do I change datepicker format from DD MM to YYYY?

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);


1 Answers

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/

like image 171
doitlikejustin Avatar answered Sep 29 '22 19:09

doitlikejustin