Convert JSON date to JavaScript date in angular

Dealing with dates is always a nightmare. In this example I will show how to convert a JSON date to JavaScript date returned from server side to an AngularJS app.

In AngularJS we use filters to transform data, in this case we can use angular date filter. But it doesn’t work directly with JSON formatted dates.

JSON Date format: /Date(milliseconds)/

I am going to write a custom filter which uses angular built in date filter and accepts the JSON date as well as the required output format. Filter will read the input and extracts parts of a JSON date using substr() method and coverts into integer and pass it as input to angular date filter along with output date format.

Here sample controller sets a date directly to variable on the $scope for simplicity in example.


angular.module('jsonDateConverterExample', [])
  .controller('JsonDateController', ['$scope', function($scope) {
    $scope.sampleJsonDate = '\/Date(1433913313004-0800)\/';
  }]);

Here is the angular filter which accepts JSON date.


angular.module('jsonDateConverterExample', [])
  .filter('jsonDate', ['$filter', function ($filter) {
    return function (input, format) {
        return (input) 
               ? $filter('date')(parseInt(input.substr(6)), format) 
               : '';
    };
 }]);

Here is the html which uses JSON date filter to display the JSON date in various formats of JavaScript date (Save controller and filter code into script.js file).


<!DOCTYPE html>
<html>
<head>
  <title>Angular JSON Date Converter Filter Example</title>
  <script data-require="angular.js@*" 
          data-semver="1.4.2" 
          src="https://code.angularjs.org/1.4.2/angular.js"></script>
  <script src="script.js"></script>
</head>
<body ng-app="jsonDateConverterExample">
  <h2>Angular JSON Date Converter Filter Example</h2>
  <div ng-controller="JsonDateController as dateCtrl">
    <div>
      Original JSON Date : {{sampleJsonDate}}
    </div>
    <h3>JavaScript dates in different formats :</h3>
    <div>{{ sampleJsonDate | jsonDate }}</div>
    <div>{{ sampleJsonDate | jsonDate : 'yyyy-MM-dd' }}</div>
    <div>{{ sampleJsonDate | jsonDate :'medium' }}</div>
    <div>
      {{ sampleJsonDate | jsonDate : 'yyyy-MM-dd HH:mm:ss Z' }}
    </div>
  </div>
</body>
</html>

  1. Example in Plunker
  2. Example in Github Repo

2 thoughts on “Convert JSON date to JavaScript date in angular

  1. Thank you for posting this! I was having a heck of a time figuring out a good way to convert these odd dates. thanks again.

Leave a Reply