Tag Archives: Knockout

Formatting Dates with Knockout.js

I am working on a couple of Silverlight projects using Microsoft Prism and found the MVVM pattern very powerful. The team at work is developing a single page HTML/Javascript application that is using Knockout as the MVVM framework. I wanted to bind a date using a custom format ‘dddd, MMMM dd, yyyy’. Since JavaScript doesn’t have great support for formatting dates I pulled in Date.js.

I am familiar with using IValueConverter in Silverlight to convert values during binding. I was really happy to find a the custom binding feature in Knockout called ‘bindingHandlers‘. I was able to write a quick bindingHandler to format the date using date.js.

Checkout the Demo

Here is the custom binding for formatting dates using date.js:

ko.bindingHandlers.dateString = {
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        var value = valueAccessor(),
            allBindings = allBindingsAccessor();
        var valueUnwrapped = ko.utils.unwrapObservable(value);
        var pattern = allBindings.datePattern || 'MM/dd/yyyy';
        $(element).text(valueUnwrapped.toString(pattern));
    }
}

Here is the binding in page:

Thursday, April 05, 2012
0.00