javascript 在淘汰赛模板中格式化日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17455784/
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
Formatting Date in Knockout Template
提问by rross
I'm wanting to format a date in knockout's template. The date is currently being returned as
我想在淘汰赛模板中格式化日期。日期当前返回为
2013-07-04T00:00:00
I would like it to be displayed like
我希望它显示为
07/04/2013
Here is the binding I'm using
这是我正在使用的绑定
<td data-bind="text: FirstDate">
Are their default formatting properties in Knockout's template?
它们的默认格式属性是否在 Knockout 的模板中?
回答by nemesv
There is nothing built in regarding date formatting or formatting in general in Knockout. The text
binding just converts the property value to string so if you want custom formatting you need to do it yourself.
在 Knockout 中没有内置任何关于日期格式或格式的内容。将text
结合刚刚转换属性值字符串所以如果你想自定义格式,你需要自己做。
Working with dates is not so easy in JavaScript so you are probably better with using a third party library like moment.jsfor this. It is very simple to use and it can format your dates with the format
method. There is built in format 'L'
for your required Month numeral, day of month, year formatting.
在 JavaScript 中处理日期并不是那么容易,因此使用像moment.js这样的第三方库可能会更好。它使用起来非常简单,它可以使用format
方法格式化您的日期。'L'
您需要的月份数字、月份日期、年份格式都有内置格式。
You can use moment js in your view-model or directly in your binding like:
您可以在视图模型中或直接在您的绑定中使用 moment js,例如:
<td data-bind="text: moment(FirstDate).format('L')">
Or you can create a custom binding handler which encapsulates this formatting logic.
或者,您可以创建一个自定义绑定处理程序来封装此格式化逻辑。
Note: Make sure to use ()
on your FirstDate
property if it is an ko.observable
inside your data-binding expression to get its value.
注意:确保()
在您的FirstDate
属性上使用,如果它ko.observable
在您的数据绑定表达式中以获取其值。
回答by Corey Cole
I use moment.js in a modified version of Stephen Redd's date extender. It looks like this, which is a little cleaner than calling a function in a data bind.
我在Stephen Redd 的日期扩展器的修改版本中使用 moment.js 。看起来像这样,这比在数据绑定中调用函数要简洁一些。
<input type="text" data-bind="value: dateOfBirth.formattedDate" />
回答by Mason240
You can also use MomentJs to create an extender:
您还可以使用 MomentJs 创建扩展器:
ko.extenders.date = function (target, format) {
return ko.computed({
read: function () {
var value = target();
if (typeof value === "string") {
value = new Date(value);
}
return moment(value).format("LL");
},
write: target
});
}
viewmodel:
视图模型:
self.YourDate = ko.observable().extend({ date: true });