Jason O.
Jason O.

Reputation: 3310

Issue with Javascript date format passed by ng-model

I'm new to AngularJS, and struggling with a seemingly simple issue. A date value input through ng-model to the ng-controller reads differently (see below) between IE (v8/9/10) and Chrome. This inconsistency makes it difficult to write the code to handle the date on the server end (Python).

How can I make this consistent? (preferably IE format because " GMT-0700 (Pacific Daylight Time)" is not easy to parse into datetime on the server. Thanks in advance.

HTML:

<div id="td_date"  ><datepicker type="text" id="newdate" ng-model="data.date" name="date" bs-datepicker ></div>
Selected date: {{data.date}}  -----> **This prints 2014-09-21T07:10:45.117Z in both browsers**

JS:

function ($scope, $log, data) {

   $log.info('date ='+ data.date);    ----> **This prints 'Sat Sep 21 00:10:45 PDT 2014' in IE 
                       but 'Sun Sep 21 2014 00:10:45 GMT-0700 (Pacific Daylight Time)' in Chrome**
}; 

Upvotes: 1

Views: 294

Answers (2)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

when you submitting the form go through the inputs and check for the date objects and format the date to a format u prefer :) so you can get the date in exact format in the backend

    if($scope.data.date instanceof Date) {
        $scope.data.date  = $filter('date')($scope.data.date , "yyyy-MM-dd"); // filter to a format u like
    }

if your form is in data object like data.date,'data.userName'... You can use that as follows When submitting the form,

for (key in $scope.data) {
    $scope.data[key] instanceof Date) {
        $scope.data[key] = $filter('date')($scope.data[key], "yyyy-MM-dd"); // filter to a format u like
    }
}

here is the api for the date filters in angularjs https://docs.angularjs.org/api/ng/filter/date

Upvotes: 3

micronyks
micronyks

Reputation: 55443

function ($scope, $log, data, $filter) {

   $log.info('date ='+ $filter('date')(data.date,'dd-MM-yyyy');   
}; 

Use $filter service of angularjs. for more info: https://docs.angularjs.org/api/ng/filter/date

Upvotes: 1

Related Questions