Keywords: AngularJS | UTC | date filter | timezone | JavaScript
Abstract: This article explains how to handle UTC timestamps in AngularJS when using the date filter, which by default adds local timezone information. It covers both custom solutions and built-in methods from Angular versions 1.3.0 onwards.
Introduction
When using AngularJS's date filter to render timestamps, developers often encounter issues with timezone offsets being added automatically. This article provides solutions to output UTC timestamps correctly.
Understanding the Problem
The date filter in AngularJS appends the local timezone information to the output when formats like "Z" are used. For example, a Unix timestamp 1400167800 (representing May 15, 2014, 3:30 PM UTC) might be displayed as 15-5-2014 17:30 +0200 in a local timezone.
Custom Solution Using JavaScript Functions
Based on the accepted answer, a common approach is to create custom functions in the controller to convert dates to UTC. Here's an example:
// Controller code
var app1 = angular.module('app1', []);
app1.controller('ctrl', ['$scope', function($scope) {
var toUTCDate = function(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
};
var millisToUTCDate = function(millis) {
return toUTCDate(new Date(millis));
};
$scope.millisToUTCDate = millisToUTCDate;
}]);In the template:
{{ millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm' }}This ensures the output is in UTC without timezone offset.
Built-in Solution with Angular 1.3.0+
Starting from AngularJS version 1.3.0, the date filter supports a timezone parameter. For example:
{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}This method is simpler if you are using compatible versions.
Conclusion
Depending on the Angular version and requirements, developers can choose between custom functions or the built-in timezone parameter to output UTC timestamps accurately.