【问题标题】:How to specify timezone to date filter如何指定时区到日期过滤器
【发布时间】:2013-12-30 03:11:39
【问题描述】:

我有这个日期:1386800070703。假设它是 UTC。
如何从角度判断它是哪个时区以及我希望它显示在哪个时区?

我目前正在使用 tihs,它只在没有任何时区信息的情况下进行转换:
{{1386800070703 | date:'d MMMM yyyy'}}

并且希望能够在日期右侧显示时区。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    使用元素Z

    'Z': 4 digit (+sign) representation of the timezone offset (-1200-+1200)
    
    {{1386800070703 | date:'d MMMM yyyy Z'}}
    

    【讨论】:

    • 嗯,这只会打印出机器的时区偏移量。我需要的是将该日期转换为机器的时区。我可能不得不为此编写自己的过滤器,对吧?
    【解决方案2】:

    这是我写的一个指令:

    angular.module('CommonDirectives', []).directive('adjustTimezone', ['$filter', function ($filter) {
      return {
        restrict: 'A',
        scope: {
          adjustTimezone: '@'
        },
        link: function ($scope, element, attrs) {
          var date = new Date(attrs.adjustTimezone);
    
          date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
          element.text($filter('date')(date, attrs.filter));
        }
      }
    }]);
    

    这是你如何使用它:

    <span data-adjust-timezone="{{date.MilitaryTime}}" data-filter="EEEE, MMMM d, y h:mm a"></span> 
    

    【讨论】:

      【解决方案3】:

      在 AngularJS (1.3.0) 的下一个版本中,您可以通过这种方式指定时区:

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

      目前,仅支持 UTC,您可以在文档中看到:https://code.angularjs.org/1.3.0-rc.2/docs/api/ng/filter/date

      你可以在这里玩:Plunker example

      请注意,时区将显示为本地时间,即使另有指定。

      【讨论】:

      • 为什么要这样做,然后只支持UTC?笏。
      • 自版本1.4.0-rc.0 AngularJS 也支持其他时区。例如,要获取日本标准时间,您可以使用以下命令:{{someDate | date: 'MMM d, y H:mm:ss Z' : '+0900'}}
      • 遗憾的是,Angular 2's Date pipe 不支持这个额外的时区参数。像the accepted answer for this similar question 中建议的那样在 Angular 2 中仍然有效。
      猜你喜欢
      • 1970-01-01
      • 2014-03-14
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 2022-08-22
      • 2011-09-16
      • 1970-01-01
      相关资源
      最近更新 更多