akeeseth
akeeseth

Reputation: 845

Format date in knockout

I have current date in javascript like below:

self.currentDate = ko.observable(new Date());

I want to format the date in yyyy-mm-dd and use inside Sammy like below:

this.get('', function () { this.app.runRoute('get', '#'+self.currentDate()) });

There are so many long process to do it. But is there any way to do it easily. Or can i use it inside document.ready function and used it here.

Upvotes: 1

Views: 12384

Answers (2)

Aaron Hoffman
Aaron Hoffman

Reputation: 6962

Another option is to create a custom binding handler

more info: http://jason-mitchell.com/web-development/binding-dates-using-knockout-moment-js/

ko.bindingHandlers.date = {
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
    var value = valueAccessor();
    var allBindings = allBindingsAccessor();
    var valueUnwrapped = ko.utils.unwrapObservable(value);

    // Date formats: http://momentjs.com/docs/#/displaying/format/
    var pattern = allBindings.format || 'DD/MM/YYYY';

    var output = "-";
    if (valueUnwrapped !== null && valueUnwrapped !== undefined && valueUnwrapped.length > 0) {
        output = moment(valueUnwrapped).format(pattern);
    }

    if ($(element).is("input") === true) {
        $(element).val(output);
    } else {
        $(element).text(output);
    }
}
};


<div>
    <label>Date of Birth:</label>
    <input type="text" data-bind="date: dateOfBirth, format: 'DD MMM YYYY'" />
</div>

requires moment.js: http://momentjs.com/

Upvotes: 0

Paul Alan Taylor
Paul Alan Taylor

Reputation: 10680

Take a look at datejs.

http://www.datejs.com/

It's a Javascript date library, which will handle your format conversion. It extends the toString method so that you can accomplish stuff like:-

self.currentDate().toString('yyyy-M-d')

There are a couple of options for integration with Knockout, but the above will "work" in returning a yyyy-mm-dd format.

Another approach, still using datejs, is to wrap the function in a ko.computed:-

self.displayDate = ko.computed(function(){
   return self.currentDate().toString('yyyy-M-d');
});

If you don't want to use datejs, you can roll your own and wrap it in a computed.

self.displayDate = ko.computed(function(){
   var year = self.currentDate().getFullYear().toString();
   var month = (self.currentDate().getMonth() + 1).toString();
   var day   = self.currentDate().getDay().toString();
   var pad = "00";

   return year + '-' +
     pad.substring(0, pad.length, month.length ) + month + '-' +
     pad.substring(0, pad.length, day.length ) + day;

});

But seriously, look at datejs first. Why re-invent the wheel. Can't really help you on the Sammy part, soz.

Upvotes: 2

Related Questions