0

開始日を含む期間のリストを返す JSON REST サービスがあります。開始日をJavaScriptの日付に変換するにはどうすればよいですか?

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

サービス定義で ngResource を使用しています。

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

  }

適切な日付に変換する代わりに、次のように日付を表​​示します。

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

2 に答える 2

2

Javascript 日付に変換:

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

period.startDate[1]-1月は (1 月) に始まり(12 月)0に終わるため、使用したことに注意してください11

日付を 1 回だけ処理するには、次のスニペットをsuccessコールバックに追加します。

angular.forEach($scope.periods, function (period) {
    period.startDate = new Date(period.startDate[0], period.startDate[1]-1, period.startDate[2]);
});
于 2013-02-06T14:18:25.730 に答える
1

どうもありがとう。それは完全に機能します!

ノート。new Date() に配列を提供するときに、月数から -1 を引く必要はありません。

 new Date([2012, 12, 24]) === new Date(2012, 11, 24);
于 2013-02-07T09:56:34.797 に答える