Angular: date filter adds timezone, how to output UTC? Angular: date filter adds timezone, how to output UTC? angularjs angularjs

Angular: date filter adds timezone, how to output UTC?


Since version 1.3.0 AngularJS introduced extra filter parameter timezone, like following:

{{ date_expression | date : format : timezone}}

But in versions 1.3.x only supported timezone is UTC, which can be used as following:

{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}

Since version 1.4.0-rc.0 AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):

{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}

Here you can find documentation of AngularJS date filters.

NOTE: this is working only with Angular 1.x

Here's working example


The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.

Borrowing from this answer, you could do something like this without moment.js:

controller

var app1 = angular.module('app1',[]);app1.controller('ctrl',['$scope',function($scope){  var toUTCDate = function(date){    var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());    return _utc;  };  var millisToUTCDate = function(millis){    return toUTCDate(new Date(millis));  };    $scope.toUTCDate = toUTCDate;    $scope.millisToUTCDate = millisToUTCDate;  }]);

template

<html ng-app="app1">  <head>    <script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>    <link rel="stylesheet" href="style.css" />    <script src="script.js"></script>  </head>  <body>    <div ng-controller="ctrl">      <div>      utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}      </div>      <div>      local {{1400167800 | date:'dd-M-yyyy H:mm'}}      </div>    </div>  </body></html>

here's plunker to play with it

See also this and this.

Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.


The date filter always formats the dates using the local timezone. You'll have to write your own filter, based on the getUTCXxx() methods of Date, or on a library like moment.js.