twitter-bootstrap Bootstrap datepicker 格式日期显示与值不同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29021207/
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
Bootstrap datepicker format date differently on display than on value
提问by Captain Stack
I want to use Twitter Bootstrap's datepicker. I want the actual input to DISPLAY in the format mm/dd/yyyy but the value of the object I want it to create/pass should be in yyyy-mm-dd. I am aware of this property:
我想使用 Twitter Bootstrap 的日期选择器。我想要格式为 mm/dd/yyyy 的 DISPLAY 的实际输入,但我希望它创建/传递的对象的值应该在 yyyy-mm-dd 中。我知道这个属性:
"data-date-format" => "mm-dd-yyyy"
But that changes both the way the date is displayed and how the value is formatted. I also have this in my JS:
但这会改变日期的显示方式和值的格式。我的 JS 中也有这个:
$(this).datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
todayHighlight: true,
pickTime: false
});
I'm not really sure what the format part is doing, but changing it doesn't change the value that is created by the input.
我不太确定格式部分在做什么,但更改它并不会更改由输入创建的值。
采纳答案by Sahar Zehavi
there's a solution from bootstrap for this problem.
bootstrap 有一个解决方案可以解决这个问题。
as said on the docs
正如文档中所说
you can set format as an object with 2 parsing functions: toValue and toDisplay.
您可以将格式设置为具有 2 个解析函数的对象:toValue 和 toDisplay。
$('.datepicker').datepicker({
format: {
/*
* Say our UI should display a week ahead,
* but textbox should store the actual date.
* This is useful if we need UI to select local dates,
* but store in UTC
*/
toDisplay: function (date, format, language) {
var d = new Date(date);
d.setDate(d.getDate() - 7);
return d.toISOString();
},
toValue: function (date, format, language) {
var d = new Date(date);
d.setDate(d.getDate() + 7);
return new Date(d);
}
},
autoclose: true
});
回答by Jared Clemence
When I am faced with such a problem, where I want data displayed differently than I want it communicated, I usually write a short script to copy the value into a hidden element where I maintain the 'correctly'-formatted data which the user does not see.
当我遇到这样的问题时,我希望数据显示的方式与我希望传达的数据不同,我通常会编写一个简短的脚本将值复制到一个隐藏元素中,在那里我维护用户不知道的“正确”格式的数据看。
This is the best solution I can offer at the moment, as I do not know of any way to convince the Bootstrap Datepicker to use two formats simultaneously.
这是我目前可以提供的最佳解决方案,因为我不知道有什么方法可以说服 Bootstrap Datepicker 同时使用两种格式。

