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

4

17

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.

Terracotta answered 12/8, 2013 at 20:10 Comment(0)
S
19

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/

Samalla answered 12/8, 2013 at 20:13 Comment(5)
Thanks. I actually omitted some things. The wrapping div includes a <span class="add-on">Terracotta
I see. Did adding the data-date-format to the input fix the issue, or is it still happening?Samalla
Still happening. The getDate method still returns an object. It's a different object now, and appears to be part of the DOM. (The input perhaps?)Terracotta
@Terracotta Here is a link that shows the results jsfiddle.net/doitlikejustin/HFuDg/1 I also updated my answerSamalla
I want to collect multiple dates in my datepicker using var nbworkersdate = $('.nbworkersDate',r).datepicker("getDates") and what I get is a list of todays dates not the ones insertted. Why?Fanestil
U
11
var value = $("#myDate").datepicker("getFormattedDate");
Urger answered 9/8, 2018 at 22:30 Comment(1)
This is an undocumented method and works perfectly. Especially when the date picker is embedded (<div> instead of an <input>).Woofer
W
2

If you want the value as a string use: var value = $("#myDate input").val();

The method getDate returns an object

Week answered 5/4, 2018 at 11:37 Comment(1)
version 1.9.0 does not return an objectAbohm
A
1

you can use:

$("#myDate").data('datepicker').getFormattedDate('yyyy-mm-dd');

you will have it in prover format even if you set a different format to display the data for users like this

<input id="myDate" type="text" data-date-format="MM/DD/YYYY">
Abohm answered 9/6, 2021 at 4:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.