13

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?

rross
  • 2,236
  • 11
  • 36
  • 41
  • 1
    There is nothing built in Knockout regarding date formatting or formatting in general. You need to use a thrid party library like [moment.js](http://momentjs.com/) for this. – nemesv Jul 03 '13 at 18:45
  • Thanks @nemesv I included moment.js. . Does exactly what I wanted. – rross Jul 03 '13 at 18:51

3 Answers3

29

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.

Edward Brey
  • 40,302
  • 20
  • 199
  • 253
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • @lola the available format options are listed in the moment.js documentation: http://momentjs.com/docs/#/displaying/format/ – nemesv Nov 24 '16 at 08:41
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" />
Corey Cole
  • 977
  • 9
  • 18
0

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/

Mason240
  • 2,924
  • 3
  • 30
  • 46