thomasfl
thomasfl

Reputation: 159

How to convert part of json respons to javascript date using angular?

I have a JSON REST service that returns a list of periods with start dates. How can I convert the start date to javascript date?

  [ {
      "periodId": 1234, 
      "startDate": [ 2011, 12, 24]
    }, 
    {
      "periodId": 5678, 
      "startDate": [ 2012, 12, 24]
    }
   ]

I'm using ngResource in my service definition:

  angular.module('periodservice',['ngResource']).
     factory('Periods', function($resource) {
      return $resource('../rest/periods', {}, {
        query : {method : 'GET', params : {}, isArray : true}
      });
    });

The controller is pretty straight forward.

  function EksternVareRedigeringCtrl ($scope, Periods){

    $scope.periods = Periods.query(function(success, status, headers){
      $scope.msgf = success;
      console.log("this is the succsess);
    }, function(errors){
      $scope.msgf = errors;
      console.log("This is an error....." + ' ' + $scope.msgf.status);
    });

  }

Now I display the date like this instead of converting it to a proper date:

   <div class="period">Period: {{period[0]}}-{{period[1]}}-{{period[2]}}</div>

Upvotes: 0

Views: 1146

Answers (2)

thomasfl
thomasfl

Reputation: 159

Thanks a lot. It works perfectly!

Note. You do not have to subtract -1 from month number when supplying an array to new Date():

 new Date([2012, 12, 24]) === new Date(2012, 11, 24);

Upvotes: 1

bmleite
bmleite

Reputation: 26880

Convert to Javascript Date:

new Date(period.startDate[0], period.startDate[1]-1, period.startDate[2])

Note that I've used period.startDate[1]-1 because the months start at 0 (January) and end at 11 (December).

To process the dates only once, add the following snippet to your success callback:

angular.forEach($scope.periods, function (period) {
    period.startDate = new Date(period.startDate[0], period.startDate[1]-1, period.startDate[2]);
});

Upvotes: 2

Related Questions