Date Serialization With AngularJS & Web API

When we use the Web API to get or post data from a web page (HTML page) using AngularJs, it is very essential to maintain the data type formatting to get or post the proper value, since data is sent or received as JSON data. Now JSON reads all data types properly except the date datatype because JSON does not have any native date / time data type on its own. So when we parse any data containing a date time data type, it does not convert in proper format in JSON. A JSON date comes in a format that isn't directly convertable to JavaScript date objects (for example, /Date(1349301600000+0200)/ ). This can cause a bit of a headache. The following is the discussion for converting the date properly.
 
For doing this, we need to first create our web API controller. For that, we will first create a new class named Employee as in the following:
  1. public class Employee    
  2. {    
  3.     public int SrlNo { getset; }    
  4.     public string EmployeeName { getset; }    
  5.     public string City { getset; }    
  6.     public int Age { getset; }    
  7.     public DateTime DOB { getset; }    
  8.     public decimal GrossSalary { getset; }    
  9. }  
Now we add a API controller named EmployeeController and add the following code there:
  1. public class EmployeeController : ApiController    
  2. {    
  3.     [HttpPost]    
  4.     public List<Employee> post()    
  5.     {    
  6.         return PopulateEmpData();    
  7.     }    
  8.   
  9.     private List<Employee> PopulateEmpData()    
  10.     {    
  11.         List<Employee> lstData = new List<Employee>();    
  12.   
  13.         lstData.Add(new Employee    
  14.         {    
  15.             SrlNo = 1,    
  16.             EmployeeName = "Suman",    
  17.             City = "New Delhi",    
  18.             Age = 30,    
  19.             DOB = Convert.ToDateTime("1985-10-25"),    
  20.             GrossSalary = 20000    
  21.         });    
  22.   
  23.         lstData.Add(new Employee    
  24.         {    
  25.             SrlNo = 2,    
  26.             EmployeeName = "Arnab",    
  27.             City = "Lucknow",    
  28.             Age = 25,    
  29.             DOB = Convert.ToDateTime("1990-05-02"),    
  30.             GrossSalary = 15000    
  31.         });    
  32.   
  33.         lstData.Add(new Employee    
  34.         {    
  35.             SrlNo = 3,    
  36.             EmployeeName = "Tapas",    
  37.             City = "Kolkata",    
  38.             Age = 40,    
  39.             DOB = Convert.ToDateTime("1975-03-01"),    
  40.             GrossSalary = 000    
  41.         });               
  42.   
  43.         return lstData;    
  44.     }    
  45. }  
Now for the AngularJs part. Add a blank HTML file named EmpInfo.Html and provide the following code: 
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title>Employee List</title>  
  5.     <script src="../Script/angular1.3.8.js"></script>  
  6.     <script src="../Script/angular-route.js"></script>  
  7.     <script src="../UserScript/MyApp.js"></script>  
  8.     <script src="../UserScript/EmpController.js"></script>  
  9. </head>  
  10. <body ng-app="MyApp" ng-controller="EmpController">  
  11.     <div>  
  12.         <div>  
  13.             <input type="button" value="Serialize Data" ng-click="fnButton1();" />  
  14.             <input type="button" value="Deserialize Data" ng-click="fnButton2();" />  
  15.         </div>  
  16.         <div>  
  17.             <h1>Data Before Deserialize</h1>  
  18.             <table style="width:100%;border:solid ;border-style:solid">  
  19.                 <tr>  
  20.                     <td>SrlNo</td>  
  21.                     <td>Employee Name</td>  
  22.                     <td>City</td>  
  23.                     <td>Age</td>  
  24.                     <td>Date of Birth</td>  
  25.                     <td>Gross Salary</td>  
  26.                 </tr>  
  27.                 <tr ng-repeat="var in EmpData">  
  28.                     <td>{{var.SrlNo}}</td>  
  29.                     <td>{{var.EmployeeName}}</td>  
  30.                     <td>{{var.City}}</td>  
  31.                     <td>{{var.Age}}</td>  
  32.                     <td>{{var.DOB}}</td>  
  33.                     <td>{{var.GrossSalary}}</td>  
  34.                 </tr>  
  35.             </table>  
  36.         </div>  
  37.         <div>  
  38.             <h1>Data After Deserialize</h1>  
  39.             <table style="width:100%;border:solid ;border-style:solid">  
  40.                 <tr>  
  41.                     <td>SrlNo</td>  
  42.                     <td>Employee Name</td>  
  43.                     <td>City</td>  
  44.                     <td>Age</td>  
  45.                     <td>Date of Birth</td>  
  46.                     <td>Gross Salary</td>  
  47.                 </tr>  
  48.                 <tr ng-repeat="var1 in EmpDeSerializeData">  
  49.                     <td>{{var1.SrlNo}}</td>  
  50.                     <td>{{var1.EmployeeName}}</td>  
  51.                     <td>{{var1.City}}</td>  
  52.                     <td>{{var1.Age}}</td>  
  53.                     <td>{{var1.DOB |  date:"MM/dd/yyyy"}}</td>  
  54.                     <td>{{var1.GrossSalary}}</td>  
  55.                 </tr>  
  56.             </table>  
  57.         </div>  
  58.     </div>  
  59. </body>  
  60. </html>  
Here we use MyApp as ng-app and EmpController as controller. In the page, we are creating two tables containing the same data. The first table contains the data without deserialization for datetime and the second table displays the deserialized data.
 
For doing it, we first create a JavaScript file MyApp.Js and define the Angular App within it. The code is as in the following:
  1. var MyApp = angular.module('MyApp', []);  
Now to define the Controller of AngularJs. For that, add another AngularJs file named EmpController.JS with the following code:
  1. MyApp.controller("EmpController", ['$scope''$http',  
  2.     function ($scope, $http, $location) {          
  3.         $scope.fnButton1 = function () {  
  4.             $http.post("http://localhost:59553/api/Employee")  
  5.                 .then(function (response) {  
  6.                     $scope.EmpData = response.data;  
  7.                 });  
  8.         }  
  9.     }  
  10. ]);  
Now run the code in the browser. After clicking on the Serialize button, the following result will be displayed.
 
Here it is clearly shown that the value of the date of birth comes from the Web API with serialized format. JSON can't automatically deserialize the data. For doing this serialization we need to create a regular expression and convert the date value into proper format. For doing that, we will define a function for converting the datetime value as in the following within the EmpController.JS file.
  1. var iso8601RegEx = /(19|20|21)\d\d([-/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])T(\d\d)([:/.])(\d\d)([:/.])(\d\d)/;  
  2.   
  3. function fnConverDate(input) {  
  4.     if (typeof input !== "object"return input;  
  5.   
  6.     for (var key in input) {  
  7.         if (!input.hasOwnProperty(key)) continue;  
  8.   
  9.         var value = input[key];  
  10.         var type = typeof value;  
  11.         var match;  
  12.         if (type == 'string' && (match = value.match(iso8601RegEx))) {  
  13.             input[key] = new Date(value)  
  14.         }  
  15.         else if (type === "object") {  
  16.             fnConverDate(value);  
  17.         }  
  18.     }  
  19. }  
In the preceding code, we defined a regular expression for date format and in the function, we saw that the id of the item value is matched with this regular expression, then it is deserialized into date format. We will now write the function for the second button within the EmpController as in the following code.
  1. MyApp.controller("EmpController", ['$scope''$http',  
  2.     function ($scope, $http, $location) {          
  3.         $scope.fnButton1 = function () {  
  4.             $http.post("http://localhost:59553/api/Employee")  
  5.                 .then(function (response) {  
  6.                     $scope.EmpData = response.data;  
  7.                 });  
  8.         }  
  9.   
  10.         $scope.fnButton2 = function () {  
  11.             $http.post("http://localhost:59553/api/Employee")  
  12.                 .then(function (response) {  
  13.                     fnConverDate(response.data);  
  14.                     $scope.EmpDeSerializeData = response.data;                      
  15.                 });  
  16.         }  
  17.     }  
  18. ]);  
After writing this code, now execute the following project and click on both buttons to see the following output.

The first table displays the data with serialized date format value.
The second table displays the data with the deserialized date type value. 

Up Next
    Ebook Download
    View all
    Learn
    View all