在Knockout模板中格式化日期 [英] Formatting Date in Knockout Template

查看:414
本文介绍了在Knockout模板中格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在淘汰赛模板中格式化日期。
日期当前正在返回

I'm wanting to format a date in knockout's template. The date is currently being returned as

2013-07-04T00:00:00

我希望它显示为

07/04/2013

这是我正在使用的绑定

<td data-bind="text: FirstDate">

它们是Knockout模板中的默认格式属性吗?

Are their default formatting properties in Knockout's template?

推荐答案

Knockout中一般没有内置日期格式或格式。 text 绑定只是将属性值转换为字符串,因此如果您想要自定义格式,则需要自己完成。

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.

在JavaScript中使用日期并不是那么容易,所以使用像 moment.js 。它使用起来非常简单,它可以使用 格式<来格式化您的日期/ code>方法。内置格式'L'表示您所需的月份数字,日期,年份格式。

Working with dates is not so easy in JavaScript so you are probably better with using a third party library like moment.js for 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.

您可以在视图模型中使用时刻js,也可以直接在绑定中使用:

You can use moment js in your view-model or directly in your binding like:

<td data-bind="text: moment(FirstDate).format('L')">

或者你可以创建一个封装这种格式化逻辑的自定义绑定处理程序。

Or you can create a custom binding handler which encapsulates this formatting logic.

注意:确保在 FirstDate 属性中使用()(如果它是在数据绑定表达式中 ko.observable 以获取其值。

Note: Make sure to use () on your FirstDate property if it is an ko.observable inside your data-binding expression to get its value.

这篇关于在Knockout模板中格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆