AngularJ中的日期以$resource.$ save()发送在UTC中



我对angularjs有问题。我创建了一个工厂活动,当我使用$ Save Metho时,d日期是在UTC中发送的,而不是在浏览器时区...

我创建了一个JSFIDDLE来说明它:

http://jsfiddle.net/wr8ml/

(单击"保存"按钮并打开控制台以查看请求参数)

我的代码:

window.App = angular.module('App', ["ngResource"]);
App.factory('Event', ['$resource', '$http', function($resource, $http) {
  Event = $resource('/events/:id.json',
      { id:'@id' },
      { update: {method:'PUT' }, 'query': { method: 'GET', isArray: false }});
  return Event;
}])
App.controller("EventNewCtrl", ['$scope', "$http", "Event", function($scope, $http, Event) {
  $scope.resetEvent = function(){
    $scope.event = new Event({ date: new Date() })
  }
  $scope.save = function() {
      $scope.event.$save();
  }
  $scope.resetEvent()
}]);

在提交数据之前,Angular使用JSON.STRINGIFY函数转换您的对象。尝试

console.log(JSON.stringify(new Date()));

这与:

相同
console.log(new Date().toISOString());

(可以肯定的是第一个将用引号包装)

改变默认行为有很多可能性:

1)用自己的实现替换Toisostring函数:

  Date.prototype.toISOString = function(){
      return 'here goes my awesome formatting of Date Objects '+ this;
  }; 

2)用自己的默认转换替换了Angular的默认转换。您可以通过提供TransformRequest函数(每个资源配置或$httpProvider.defaults.transformRequest的完整应用程序)来做到这一点。有关更多信息,请参见$ HTTP服务。您的功能看起来像这样:

transformRequest: function(data){
    return your string representation of the data
}

如果您有兴趣,为什么toisodate strips timezone the ecmascript langauge规范:http://www.ecma-international.org/ecma-262/5.1/#sec-1.1.1.1.1.1.1.15

相关内容

最新更新