Search code examples
javascriptangularjsangular-resource

AngularJS convert Date to getTime() before sending to server


I have a form that uses <input type="datetime-local" ng-bind="course.endDate".. and sets a variable of the model. Before sending the date to the server I've to convert the date 2015-04-04T22:00:00.000Z to a integer given by the getTime().

In the controller i added this: course.endDate = course.endDate.getTime(); it works for the server side but angular complains in the console with this error. (as said, it works, but I would like to avoid errors)

Error: [ngModel:datefmt] Expected `1325458800000` to be a date
http://errors.angularjs.org/1.3.15/ngModel/datefmt?p0=1325458800000
    at REGEX_STRING_REGEXP (angular.js:63)
    at Array.<anonymous> (angular.js:19938)
    at Object.ngModelWatch (angular.js:23419)
    at Scope.$get.Scope.$digest (angular.js:14300)
    at Scope.$get.Scope.$apply (angular.js:14571)
    at done (angular.js:9698)
    at completeRequest (angular.js:9888)
    at XMLHttpRequest.requestLoaded (angular.js:9829)

How can i do then?

I had the idea of adding some fields that are used in the form (formEndDate) and convert to another one (endDate = formEndDate.getTime()) for the server side, but in this way the server refuse the call since the parameter formEndDate is not allowed, and if I remove the formEndDate then everything breaks.

additional problem: When i fetch data from the server I have an integer that needs to be converted into a date to be used in the form. so I've to convert the date also before allowing an edit. how can I do this? (the data fetched are into an array, so would be terrific to have the conversion without having to iterate on the whole array)

solution

thanks to the two answers (I set correct the first that came) I also (somehow) solved the problem of the form when editing. I did so by creating an extra field and use it for the form when editing (I do inline editing).

I created a gist here


Solution

  • Before sending the data to the server, make a copy and set endDate. Then send the copy to the server:

    var courseCopy = angular.copy(course);
    courseCopy.endDate = courseCopy.endDate.getTime();