Formatting Date in Knockout Template

rross picture rross · Jul 3, 2013 · Viewed 21.1k times · Source

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?

Answer

nemesv picture nemesv · Jul 3, 2013

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.