rross
rross

Reputation: 2276

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 binding I'm using

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

Are their default formatting properties in Knockout's template?

Upvotes: 13

Views: 22204

Answers (3)

Mason240
Mason240

Reputation: 3044

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/

Upvotes: 0

nemesv
nemesv

Reputation: 139818

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.

Upvotes: 29

Corey Cole
Corey Cole

Reputation: 987

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

Upvotes: 2

Related Questions