Search code examples
jsonjqueryhandsontable

Where can I convert JSON date format when data from WCF ajax call?


I am getting JSON data from WCF service like below format. Then I am binding that data to handsOnTables.

JSON

{"d":[
  { "__type":"InitData:#company.ReductionData",
    "Owner":"test9",
    ...
    ... 
    "StartDate":"\/Date(1366848000000+0000)\/",
    "Risks":"test9",
 }] }

JSCript

$(function () {

         var $value = $("#Body_hiddenClientId");
        // alert($value.val());
         var $container = $("#dataTable");

         $container.handsontable({
             contextMenu: true,
             startRows: 1,
             minRows: 1,                 
             colHeaders: true,
             stretchH: 'all',     
             columns: [
                 { data: 'Owner' },
                 ...
                 ....
                 { data: 'StartDate', type: 'date', dateFormat: 'mm/dd/yy' },
                 { data: 'Risk' }                   
               ]
         });

         var handsontable = $container.data('handsontable');
         $.ajax({
             url: "/EditInitiatives.svc/GetGridData",
             data: "session=" + $value.val(),
             type: "GET",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: function (res) {                   
                 $container.handsontable('loadData', res.d);    
             },
             error: function (error) {
                 alert("Error: " + error.responseText);
             }
         });
     });

I don't know How to convert into 'mm/dd/yy' format? Where to convert format in the code?


Solution

  • handsontable expects a string to format date. you should convert it to the proper form.

    try something like this:

    change this:

    ...
    success: function (res) {                  
        $container.handsontable('loadData', res.d);    
    },
    ...
    

    with this:

    ...
    success: function (res) {
        for(var i in res.d) {
            // get the milliseconds from your string "StartDate":"\/Date(1366848000000+0000)\/",
            // and create new Date object
            var date = new Date(+(res.d[i]['StartDate'].match(/\d+/i))); 
            // then put it back with format mm/dd/yy            
            res.d[i]['StartDate'] = (date.getMonth() + 1) + '-' + date.getDate() + date.getFullYear();
        }               
        $container.handsontable('loadData', res.d);    
    },
    ...