[angularjs] Using AngularJS date filter with UTC date

I have an UTC date in milliseconds which I am passing to Angular's date filter for human formatting.

{{someDate | date:'d MMMM yyyy'}}

Awesome, except someDate is in UTC and the date filter considers it to be in local time.

How can I tell Angular that someDate is UTC?

Thank you.

This question is related to angularjs datetime angularjs-filter

The answer is


You have also the possibility to write a custom filter for your date, that display it in UTC format. Note that I used toUTCString().

_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
_x000D_
app.controller('dateCtrl', function($scope) {_x000D_
    $scope.today = new Date();_x000D_
});_x000D_
    _x000D_
app.filter('utcDate', function() {_x000D_
    return function(input) {_x000D_
       return input.toUTCString();_x000D_
    };_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  _x000D_
  _x000D_
<div ng-app="myApp" ng-controller="dateCtrl">      _x000D_
    Today is {{today | utcDate}}       _x000D_
</div>
_x000D_
_x000D_
_x000D_


Could it work declaring the filter the following way?

   app.filter('dateUTC', function ($filter) {

       return function (input, format) {
           if (!angular.isDefined(format)) {
               format = 'dd/MM/yyyy';
           }

           var date = new Date(input);

           return $filter('date')(date.toISOString().slice(0, 23), format);

       };
    });

After some research I was able to find a good solution for converting UTC to local time, have a a look at the fiddle. Hope it help

https://jsfiddle.net/way2ajay19/2kramzng/20/

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="MyCtrl">
  {{date | date:'yyyy-mm-dd hh:mm:ss' }}
</div>


<script>
function MyCtrl($scope) {
 $scope.d = "2017-07-21 19:47:00";
  $scope.d = $scope.d.replace(" ", 'T') + 'Z';
  $scope.date = new Date($scope.d);
}
</script>

Here is a filter that will take a date string OR javascript Date() object. It uses Moment.js and can apply any Moment.js transform function, such as the popular 'fromNow'

angular.module('myModule').filter('moment', function () {
  return function (input, momentFn /*, param1, param2, ...param n */) {
    var args = Array.prototype.slice.call(arguments, 2),
        momentObj = moment(input);
    return momentObj[momentFn].apply(momentObj, args);
  };
});

So...

{{ anyDateObjectOrString | moment: 'format': 'MMM DD, YYYY' }}

would display Nov 11, 2014

{{ anyDateObjectOrString | moment: 'fromNow' }}

would display 10 minutes ago

If you need to call multiple moment functions, you can chain them. This converts to UTC and then formats...

{{ someDate | moment: 'utc' | moment: 'format': 'MMM DD, YYYY' }}

If you do use moment.js you would use the moment().utc() function to convert a moment object to UTC. You can also handle a nice format inside the controller instead of the view by using the moment().format() function. For example:

moment(myDate).utc().format('MM/DD/YYYY')

There is a bug filed against this in angular.js repo https://github.com/angular/angular.js/issues/6546#issuecomment-36721868


Seems like AngularJS folks are working on it in version 1.3.0. All you need to do is adding : 'UTC' after the format string. Something like:

{{someDate | date:'d MMMM yyyy' : 'UTC'}}

As you can see in the docs, you can also play with it here: Plunker example

BTW, I think there is a bug with the Z parameter, since it still show local timezone even with 'UTC'.


An evolved version of ossek solution

Custom filter is more appropriate, then you can use it anywhere in the project

js file

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

myApp.filter('utcdate', ['$filter','$locale', function($filter, $locale){

    return function (input, format) {
        if (!angular.isDefined(format)) {
            format = $locale['DATETIME_FORMATS']['medium'];
        }

        var date = new Date(input);
        var d = new Date()
        var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
        return $filter('date')(_utc, format)
    };

 }]);

in template

<p>This will convert UTC time to local time<p>
<span>{{dateTimeInUTC | utcdate :'MMM d, y h:mm:ss a'}}</span>

If you are working in .Net then adding following in web.config inside

<system.web>

will solve your issue:

<globalization culture="auto:en-US" uiCulture="auto:en-US" />

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to angularjs-filter

Angular.js ng-repeat filter by property having one of multiple values (OR of values) Using AngularJS date filter with UTC date Limit the length of a string with AngularJS Descending order by date filter in AngularJs ng-repeat :filter by single field filters on ng-model in an input