Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js format date item

In my view I wish to display a knockout.js binded field that contains a date. It is just a display field and not an input field. Something like below when basemodel.actionDate = ko.observable()

<p class="display-field" data-bind="text: baseModel.actionDate"/> 

However this is displayed as follows:

2013-06-17T11:56:18.4537687Z

What is the easiest way to format this dd mm yyyy. eg: 17 June 2013?

like image 293
Martin Avatar asked Jun 17 '13 13:06

Martin


2 Answers

I recommend the moment.js date formatting library.

Using it, you can do something like this in your view:

<p class="display-field" data-bind="text: moment(baseModel.actionDate()).format('LL')"/>
like image 140
Brandon Avatar answered Nov 01 '22 07:11

Brandon


Either make sure the service output it in a correct format, or format in client side

If you want todo it client side then you can parse the ISO date string into a Date object and then use jQuery globalize to format it to desired format.

I use KO extenders for this

http://jsfiddle.net/vRf5B/42/

ko.extenders.date = function(target, format) {
    return ko.computed({
        read: function() {
            var value = target();
            if(typeof value === "string") {
                value = new Date(value);                
            }

            format = typeof format === "string" ? format: undefined;
            value = Globalize.format(value, format);

            return value;        
        },
        write: target
    });
}

update

I got a question on my blog how to retrieve the raw date value It can be done my exposing the raw value on the computed like

http://jsfiddle.net/vRf5B/91/

like image 13
Anders Avatar answered Nov 01 '22 07:11

Anders