Saturday, March 10, 2012

JSON dates and Knockout.js date binding

JSON data for date data types is returned as a string in the following format;

\/Date(1330731072583)\/

If you are using Knockout.js for client-side data binding, a simple value binding will result in the same date string being displayed on the data bound control. To properly handle this a custom date binding can be created.

ko.bindingHandlers.date = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        try {
            var jsonDate = ko.utils.unwrapObservable(valueAccessor());
            var value = parseJsonDateString(jsonDate);
            var strDate = value.getMonth() + 1 + "/"
                            + value.getDate() + "/" 
                            + value.getFullYear();
            element.setAttribute('value', strDate);
        }
        catch (exc) {
        }
        $(element).change(function () {
            var value = valueAccessor();
            value(element.getAttribute('value'));
        });
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var val = valueAccessor();
        val(element.getAttribute('value'));
    }
};
The parseJsonDateString function can be defined using a regular expression.

var jsonDateRE = /^\/Date\((-?\d+)(\+|-)?(\d+)?\)\/$/;
var parseJsonDateString = function (value) {
    var arr = value && jsonDateRE.exec(value);
    if (arr) {
        return new Date(parseInt(arr[1]));
    }
    return value;
};

Use the date binding in the following way;
<input type="text" id="StartDateText" data-bind="date: StartDate" />

1 comment:

  1. Thankkkkk yoouuuuu!!!! your solution is the best man!!

    ReplyDelete