Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $http POST changes date format

Following situation:

I have a form with an input[date] field. I transform the values by following code:

$scope.entity.date = $filter('date')($scope.entity.date, 'yyyy-MM-dd');

This correctly formats the date to e.g. 2015-10-27

When I submit the entity using $http.post angular seems to recognize this as date and reformats it to 2015-09-30T23:00:00.000Z. I am in Germany and we have GMT+1. So angular converts the date to GMT. Is there any way to disable this behaviour?

Edit:

HTML-Code:

<form ng-submit="submit()">
  <input type="date" ng-model="entity.date" />
</form>

JS-Code:

$scope.submit = function() {
  $scope.entity.date = $filter('date')($scope.entity.date, 'yyyy-MM-dd');

  // when debugging this is the point where $scope.entity.date is 2015-10-27
  // so it is the format and date I expect

  $http({
    data: $scope.entity,
    method: POST,
    url: '/resource'
  })
    .success(function(data) {
      // do some stuff
    });

  // when looking into network traffic the request was sent with
  // 2015-09-30T23:00:00.000Z as value for $scope.entity.date
};
like image 630
Benny Avatar asked Oct 19 '22 23:10

Benny


1 Answers

You're changing the model value on post. Since your input type is a date, it's getting changed back. This is not a good idea, since the actual form element will change values only after you post.

Any time you need to manipulate your object before saving it's a pretty idea to create a copy of the object. That way it'll behave the way you expect.

var entity = angular.copy($scope.entity);

Then post the local copy and you should be good.

 $http({
    data: entity,
    method: POST,
    url: '/resource'
  })
like image 154
Mike Robinson Avatar answered Oct 21 '22 23:10

Mike Robinson