Pages

.Net Web Services - Json Dates

Wednesday, 14 January 2015
I'm probably not the only one that noticed this but have you ever looked at the dates that the .net json serializer returns dates?

 They look like this: \/Date(1239018869048)\/

I was working with backbone.js and mustache.js templating and needed a clean way to format the ugly dates returned above. I know you can switch the serializer to the json.net one (More details here) but that was not possible due to corporate rules. So I decided just to write a function in my backbone model that would clean it up. Here is a sample if your interested:

The Model:

var sample = Backbone.Model.extend({
    defaults: {
        Date: "",
        Subject: "",
        FormatDate: function () {
            //Format date from asp.net date (ie. /Date(1606953600000)/)
                var formatedDate = new Date(parseInt(this.Date.substr(6)));
                return $.datepicker.formatDate("dd-MM-yy",formatedDate);
            }
        }
});
  Now in the mustache template I can just use the FormatDate function in order to display a readable date like so.

 <td><div>{{ FormatDate }}</div></td>

No comments:

Post a Comment