January 4, 2012 4:25pm
Knockout Js and dates from .net 4 options

If you have a DateTime property in your Model and use the built in return Json(myModel) in your Mvc controller you will quickly realize that your “text: myDate” binding will output a gross json date “\/Date(-62135578800000)\/”

Options to Fix this display issue:

1) Create a binding that handles the conversion from the Json date to the format you desire

ko.bindingHandlers.date = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var jsonDate = valueAccessor();
        var value = new Date(parseInt(jsonDate.substr(6)));
        var ret = value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
        element.innerHTML = ret;
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {

    }
};

Usage

<td data-bind="date: DueDate">
</td>

2) Return “strings” from your Controller

return Json(new {MyDate = DateTime.Now.ToShortDateString()});

3) Use the JSON.NET to specify a Date Time format seen over at james.newtonking.com

Example

string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}

4) use JSON.parse to handle your dates as seen in this stackoverflow answer.

JSON.parse(jsonText, function(key, value) {
    // Check for the /Date(x)/ pattern
    var match = /\/Date\((\d+)\)\//.exec(value);
    if (match) {
        var date = new Date(+match[1]); // Convert the ticks to a Date object
        return humanReadable(date); // Format the date how you want it
    }

    // Not a date, so return the original value
    return value;
});

They all work, but I am still struggling with which one feels “right”.  Right now my gut is going with a mix with the binding and returning strings.  As I could see myself extending the binding to handle input with jQuery UI datepicker controls.

Liked posts on Tumblr: More liked posts »