2013-02-06 2 views
0

시작 날짜가있는 기간 목록을 반환하는 JSON REST 서비스가 있습니다. 어떻게 시작 날짜를 javascript 날짜로 변환 할 수 있습니까?각도를 사용하여 자바 스크립트 날짜로 json 응답의 일부를 변환하는 방법?

내 서비스 정의에 내가 ngResource을 사용하고
[ { 
     "periodId": 1234, 
     "startDate": [ 2011, 12, 24] 
    }, 
    { 
     "periodId": 5678, 
     "startDate": [ 2012, 12, 24] 
    } 
    ] 

:

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

컨트롤러는 매우 정직하고 있습니다.

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

    } 

은 지금은 적절한 날짜로 변환하는 대신 이런 식으로 날짜를 표시 :

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

주 나는 때문에 period.startDate[1]-1을 사용했습니다 :

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

[시작일]은 [년, 월, 일] 형식입니까? ('2012,24,14'은 유효한 날짜가 아닙니다 =)) – bmleite

+0

죄송합니다. 오타였습니다. 사실이 형식 [2012, 12, 24]입니다. 예제가 업데이트되었습니다. :-) – thomasfl

+0

$ scope.periodDate = function (마침표) {return new Date (period.startDate)} – thomasfl

답변

2

자바 스크립트 날짜로 변환 개월은 0 (1 월)부터 시작하여 11 (12 월)으로 끝납니다.

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

고마워요. 그것은 완벽하게 작동합니다! 참고. 'code' new Date ([2012, 12, 24]) === 새로운 날짜 (2012, 11, 24) === 새로운 Date()에 배열을 공급할 때 월 숫자에서 -1을 뺄 필요가 없습니다. ; 'code' – thomasfl

1

덕분에 많은 :

success 콜백에 다음 코드를 추가, 한 번만 날짜를 처리합니다. 그것은 완벽하게 작동합니다!

참고. 배열을 new Date()에 공급할 때 월수에서 -1을 뺄 필요가 없습니다.

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

생성자 new Date ([2012, 12, 24])가 IE8에서 작동하지 않습니다. – thomasfl

관련 문제