Javascript 错误:[ngModel:datefmt] 预期 `2015-05-29T19:06:16.693209Z` 是一个日期 - Angular

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30537886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:22:02  来源:igfitidea点击:

Error: [ngModel:datefmt] Expected `2015-05-29T19:06:16.693209Z` to be a date - Angular

javascriptangularjsdjangodjango-rest-framework

提问by Yehuda

I'm working on angularapplication with Djangowith rest-framework..

我正在与..一起angular申请Djangorest-framework

The app receives it's info with json from the server.. One of the keys is created_time... The value of this field is format according to iso-8601, for example 2015-05-29T19:06:16.693209Z.

该应用程序从服务器接收带有 json 的信息。其中一个键是created_time... 该字段的值是根据格式设置的iso-8601,例如2015-05-29T19:06:16.693209Z

In the client I have a field:

在客户端我有一个字段:

<input type="time" ng-model="created_time">

But when the data is arriving I get this error:

但是当数据到达时,我收到此错误:

Error: [ngModel:datefmt] Expected `2015-05-29T19:06:16.693209Z` to be a date http://errors.angularjs.org/1.3.13/ngModel/datefmt?p0=2015-05-29T19%3A06%3A16.693209Z
at REGEX_STRING_REGEXP (angular.js:63)
at Array.<anonymous> (angular.js:19807)
at Object.ngModelWatch (angular.js:23289)
at Scope.$get.Scope.$digest (angular.js:14235)
at Scope.$get.Scope.$apply (angular.js:14506)
at done (angular.js:9659)
at completeRequest (angular.js:9849)
at XMLHttpRequest.requestLoaded (angular.js:9790)

I already tried everything :( the format is exactly as the instructions in the docs of angular...

我已经尝试了一切:( 格式与 angular 文档中的说明完全相同...

回答by PSL

This must be happening with angular 1.3+. 1.3+ on wards ng-model for date/time input needs to be a valid date object, string representation of date is no longer allowed. You need to convert string to date object ($scope.created_time = new Date(dateString)) and bind it to the ng-model. If you follow the error linkit has a clear description about the error and how to resolve it.

这一定发生在 angular 1.3+ 上。1.3+ 用于日期/时间输入的病房 ng-model 需要是有效的日期对象,不再允许日期的字符串表示。您需要将字符串转换为日期对象 ( $scope.created_time = new Date(dateString)) 并将其绑定到 ng-model。如果您按照错误链接进行操作,它会清楚地描述错误以及如何解决它。

All date-related inputs like require the model to be a Date object. If the model is something else, this error will be thrown. Angular does not set validation errors on the in this case as those errors are shown to the user, but the erroneous state was caused by incorrect application logic and not by the user.

所有与日期相关的输入都要求模型是一个 Date 对象。如果模型是别的东西,就会抛出这个错误。在这种情况下,Angular 不会设置验证错误,因为这些错误会显示给用户,但错误状态是由不正确的应用程序逻辑引起的,而不是由用户引起的。

回答by Kamiel Ahmadpour

If you get your data from a REST Service, you can simply convert your fields to Date.

如果您从 REST 服务获取数据,则只需将字段转换为日期即可。

$http.get(url).success(function(data){
     $scope.data = data; // get row data
     $scope.data.mydatefield = new Date($scope.data.mydatefield); // convert filed to date
});

回答by Rodolfo Jorge Nemer Nogueira

Create a simple directive that converts the model value:

创建一个简单的指令来转换模型值:

HTML:

HTML:

<input date-input type="time" ng-model="created_time">

Directive:

指示:

app.directive('dateInput', function(){
    return {
        restrict : 'A',
        scope : {
            ngModel : '='
        },
        link: function (scope) {
            if (scope.ngModel) scope.ngModel = new Date(scope.ngModel);
        }
    }
});

回答by Andrey Klochkov

In addition to PSL's answer. This is how to override angular 1.3+ requirements to be a Date object.

除了PSL的答案。这是如何将 angular 1.3+ 要求覆盖为 Date 对象。

<input type="date" ng-model="book.date" date-format/>

<input type="date" ng-model="book.date" date-format/>

app.directive('dateFormat', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, ngModelCtrl) {
      //Angular 1.3 insert a formater that force to set model to date object, otherwise throw exception.
      //Reset default angular formatters/parsers
      ngModelCtrl.$formatters.length = 0;
      ngModelCtrl.$parsers.length = 0;
    }
  };
});

It can be used with AngularFire $firebaseObject and works fine with $bindTo 3-way binding. No need to extend $firebaseObject service. It works in Ionic/cordova applications.

它可以与 AngularFire $firebaseObject 一起使用,并且可以与 $bindTo 3 路绑定一起使用。无需扩展 $firebaseObject 服务。它适用于 Ionic/cordova 应用程序。

Working example on jsfiddle

jsfiddle 上的工作示例

Based on this answer

基于这个答案

回答by Usman

ProblemActually this is date format issue, I have resolved this issue by using this piece of code. Solution:Below piece of code will solve this issue:

问题实际上这是日期格式问题,我使用这段代码解决了这个问题。 解决方案:下面的一段代码将解决这个问题:

            var options = {
                weekday: "long", year: "numeric", month: "short",
                day: "numeric", hour: "2-digit", minute: "2-digit"
            };
            $scope.created_time = $scope.created_time.toLocaleTimeString("en-us", options);

where en-us format = "Friday?, ?Feb? ?1?, ?2013? ?06?:?00? ?AM", hope this will help others to solve issue, i was facing such error and resolved with this.

其中 en-us format = "Friday?, ?Feb? ?1?, ?2013? ?06?:?00? ?AM", 希望这能帮助其他人解决问题,我遇到了这样的错误并解决了这个问题。

回答by Eknath Kulkarni

I had this error and i directly used the object: I am posting the solution witch i carried out:
1:$userData.dob=new Date(userData.dob); 2:$scope.edit.userdob=userData.dob; before 1 i faced above error then i directly created the object and assigned it to the edit scope and the problem got resolved.

我有这个错误,我直接使用了对象:我发布了我执行的解决方案:
1:$userData.dob=new Date(userData.dob); 2:$scope.edit.userdob=userData.dob; 在 1 之前,我遇到了上述错误,然后我直接创建了对象并将其分配给编辑范围,问题得到解决。

回答by Viraj Amarasinghe

if date get reduced by 1 day, use this code,

如果日期减少 1 天,请使用此代码,

new Date(moment.utc(value).format('l LT'))

回答by vodoleq

If you need to update all dates in Array with Objects

如果您需要使用对象更新 Array 中的所有日期

var data = [
  { id: "1" , birthday: "2016-01-20T11:24:20.882Z"},
  { id: "2" , birthday: "2016-01-20T11:24:20.882Z"},
  { id: "3" , birthday: "2016-01-20T11:24:20.882Z"},
];

  function convertDataStingToObject (data) {
    for(var i=0; i < data.length; i++ ){
      console.log('string: ' + data[i].birthday);
      data[i].birthday = new Date(data[i].birthday);
      console.log('updated: ' + data[i].birthday);
      console.log(typeof(data[i].birthday));
    }

    return data;
  }

convertDataStingToObject(data);