1

Right now in knockout js I wrote a function which changes a date field to 21/2/02, this is the function

ko.bindingHandlers.formatDate = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = valueAccessor();
        var newValueAccessor = ko.unwrap(value);
        var dt = new Date(newValueAccessor);
        if (newValueAccessor != null)
            $(element).text(dt.toLocaleDateString());
    }
};

I want to know if I can change the dates to 2002-02-21.

Masnad Nihit
  • 1,986
  • 2
  • 21
  • 40

1 Answers1

0

You can write your own function to output the date how you want. Here's an example of one that you could use.

function betterDate(date) {
    date = new Date(date);
    var month = date.getMonth()+1;
    month = month < 10 ? "0" + month : month;
    var day = date.getDate();
    day = day < 10 ? "0" + day : day;
    return date.getFullYear() + "-" + month + "-" + day;
}

Put this function with the rest of your JavaScript in the binding handler (or in a higher up scope) and call it like this:

$(element).text(betterDate(dt));

This ternary statements on line 3 and 5 are because it appeared that you wanted the output to be zero-padded on the left when its a single digit. If you don't want to zero-pad the month and day just remove line 3 and 5. Another thing to note is that you do date.getMonth() + 1 because JavaScript starts months at 0 (i.e. January == 0, February == 1).

Thomasov
  • 81
  • 4