AngularJS global Date timezone offset

人走茶凉 提交于 2019-12-01 13:51:14

问题


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;
};

回答1:


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;
     }]);
}]);



回答2:


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.




回答3:


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).



来源:https://stackoverflow.com/questions/21841413/angularjs-global-date-timezone-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!