AngularJS 全局日期时区偏移 [英] AngularJS global Date timezone offset

查看:35
本文介绍了AngularJS 全局日期时区偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望显示相对于用户时区的日期.

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

我希望 Angular 有办法全局配置 Date 过滤器来做到这一点 - 必须根据具体情况手动执行此操作感觉是错误的.

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.

我的时间戳已经包含在 timestamp() 函数中(只需乘以 1000),但如果我没有我不想修改该函数em> 到.

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.

我正在这样做,并且有效,但如上所述,如果可能,我想将此级别设置得更高

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

推荐答案

因此,由于 angular 1.4.x 中的更改,这现在变得微不足道了.处理这个问题的正确方法是创建一个装饰器,在它运行之前改变内置的日期过滤器.这非常简单,并且不会对性能产生影响.

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.

这是我用的.如果没有指定时区,它只会添加一个 DEFAULT_TIMEZONE.只要没有给出其他时区,这就会将应用中的所有日期移动到 GMT.

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

这篇关于AngularJS 全局日期时区偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆