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

半世苍凉 提交于 2020-08-02 06:18:57

问题


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.


回答1:


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/




回答2:


var value = $("#myDate").datepicker("getFormattedDate");



回答3:


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

The method getDate returns an object



来源:https://stackoverflow.com/questions/18195828/bootstrap-datepicker-how-to-get-date-as-a-string-in-the-right-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!