Skip to content Skip to sidebar Skip to footer

Formatting Date In Knockout Template

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 bind

Solution 1:

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.


Solution 2:

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" />

Solution 3:

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/


Post a Comment for "Formatting Date In Knockout Template"