0

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>
3
  • Is your 'startDate' in the format [year, day, month] ? ('2012,24,14' doesn't seem to be a valid date =) ) Commented Feb 6, 2013 at 12:53
  • Sorry, it was a typo. It's actually in this format [2012, 12, 24]. The examples have been update. :-) Commented Feb 6, 2013 at 13:03
  • Find a workaround by adding $scope.periodDate = function(period){return new Date(period.startDate)} Commented Feb 6, 2013 at 13:40

2 Answers 2

2

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]);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. It works perfectly! Note. You do not have to subtract -1 from month number when supplying an array to new Date(): code new Date([2012, 12, 24]) === new Date(2012, 11, 24); code
1

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);

1 Comment

The constructor new Date([2012, 12, 24]) does not work in IE8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.