Formatting Date in Knockout Template

烂漫一生 提交于 2019-11-30 17:49:57
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.

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.

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.

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

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.

<input type="text" data-bind="value: dateOfBirth.formattedDate" />

You can also use MomentJs to create an extender:

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 });

http://momentjs.com/docs/#/displaying/format/

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