Question

I'm looking to show dates relative to the users' timezones.

My hope is that Angular has way to globally config the Date filter to do this—having to do this manually on a case-by-case basis feels wrong.

My timestamps are already wrapped in a timestamp() function (simply to multiply by 1000), but I'd prefer not to modify that function if I don't have to.

Edit:

I'm doing this, and it works, but as stated above, I'd like to set this one level higher if possible

$scope.timestamp = function (unix_time) {
    var epoch = (unix_time * 1000);
    var date = new Date();
    var localOffset = (-1) * date.getTimezoneOffset() * 60000;
    var stamp = Math.round(new Date(epoch + localOffset).getTime());
    return stamp;
};
Was it helpful?

Solution

So, thanks to changes in angular 1.4.x this is now trivial. The proper way to handle this would be to create a decorator that alters the built in date filter before it runs. This is trivially easy, and won't have an impact on performance.

This is one I use. It simply adds a DEFAULT_TIMEZONE if no timezone is specified. This has the effect of moving all dates in the app to GMT as long as no other timezone is given.

module.config(['$provide', function($provide) {
     var DEFAULT_TIMEZONE = 'GMT';

     $provide.decorator('dateFilter', ['$delegate', '$injector', function($delegate, $injector) {
       var oldDelegate = $delegate;

       var standardDateFilterInterceptor = function(date, format, timezone) {
         if(angular.isUndefined(timezone)) {
           timezone = DEFAULT_TIMEZONE;
         }
         return oldDelegate.apply(this, [date, format, timezone]);
       };

       return standardDateFilterInterceptor;
     }]);
}]);

OTHER TIPS

From official documentation:

Timezones

Keep in mind that Angular datetime filter uses the time zone settings of the browser. So the same application will show different time information depending on the time zone settings of the computer that the application is running on. Neither Javascript nor Angular currently supports displaying the date with a timezone specified by the developer.

http://docs.angularjs.org/guide/i18n

A level 'higher' could be creating a wrapper type (AKA class, ...) with your function as constructor. This should be coded at the entry point of the application for being possible using it everywhere.

Have you checked out momentjs http://momentjs.com/ ?

There's also angular-timezones, but I cannot speak to that package (https://github.com/michaelahlers/angular-timezones).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top