sathish kumar
sathish kumar

Reputation: 936

Date format is not working in angularjs

I am getting date from server in the below format.

"2017-07-10T20:51:13.000Z".

But when i am going to change the date format in "dd/MM/yyyy" format it is automatically add one more day.

Please check this plunkr.

Plunkr

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.date = '2017-07-10T20:51:13.000Z';
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="http://code.angularjs.org/1.2.14/angular.js" data-semver="1.2.14"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p ng-bind="date | date:'MM/dd/yyyy'"></p>
  </body>

</html>

My actual date is 10th July But my result i'm getting 11th July Please help me how can I resolve this issue.

Upvotes: 1

Views: 1420

Answers (2)

pgreen2
pgreen2

Reputation: 3651

I believe we are struggling with the same problem with you are at my work. The problem is timezones. The date you specified is UTC (note the Z).
But the by default, the angular filer uses the browsers's timezone. You have a couple options. The first is a bit of a hack but might work, and force the browser to render in UTC:

{{ $scope.date | datetime | 'UTC'}}

This will work for rendering date (no time portion), assuming the dates are always in UTC. Just be careful that you are always using UTC.

The bigger solution (the one we are working on at work) is to be more specific about the date-time object required. We are now using specific date only values starting from the db all the way to the front end. This eliminates the concept of timezones. Which means we no longer use standard date objects on the backend or in the front-end (ie AngularJS). So you need to create a custom filter as well as a custom input to do this correctly.

Upvotes: 1

Nainish Modi
Nainish Modi

Reputation: 488

//add custom filter
.filter('datetime', function($filter){
    return function(input){
      if(input == null){ return ""; } 

      var _date = $filter('date')(new Date(input),'MM/dd/yyyy');         
      return _date.toUpperCase();
   };
});

//html
{{ $scope.date | datetime }}

Upvotes: 2

Related Questions