twitter-bootstrap Bootstrap datepicker——如何以正确的格式将日期作为字符串获取?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18195828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 17:57:14  来源:igfitidea点击:

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

twitter-bootstrapdatepickerbootstrap-datepicker

提问by ccleve

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:

我正在使用Bootstrap datepicker。答案可能很明显,但我无法弄清楚如何将所选日期作为指定格式的字符串获取。我用了:

<div id="myDate" data-date-format="yyyy-mm-dd">
  <input type="text">
</div>

And in my javascript:

在我的 javascript 中:

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

But it returns a date, not a string in yyyy-mm-dd format.

但它返回一个日期,而不是 yyyy-mm-dd 格式的字符串。

回答by doitlikejustin

The data-date-format="mm/dd/yyyy"needs to be set on the input:

data-date-format="mm/dd/yyyy"需要在输入设置:

<input type="text" data-date-format="MM/DD/YYYY">

Your jQuery should also be changed to:

您的 jQuery 也应该更改为:

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

Or you can just keep things simple with no wrapping divand with this your original jQuery would work fine and you wouldn't have to specify input:

或者你可以保持简单而不用包装div,这样你的原始 jQuery 就可以正常工作,你不必指定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 .datepickerclass to any input field and it would work without having to specify another variable.

建议
我建议创建一个类来格式化日期选择器。这样您就可以将.datepicker类添加到任何输入字段,并且无需指定另一个变量即可工作。

Fiddle
Here is working code with alert of date http://jsfiddle.net/doitlikejustin/HFuDg/1/

Fiddle
这是带有日期警报的工作代码http://jsfiddle.net/doitlikejustin/HFuDg/1/

回答by Alexander Fedotov

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

回答by Plasebo

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

如果要将值作为字符串使用: var value = $("#myDate input").val();

The method getDate returns an object

getDate 方法返回一个对象