Using AngularJS date filter with UTC date

后端 未结 10 2280
無奈伤痛
無奈伤痛 2020-11-28 07:35

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

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

A

10条回答
  •  伪装坚强ぢ
    2020-11-28 08:04

    Similar Question here

    I'll repost my response and propose a merge:

    Output UTC seems to be the subject of some confusion -- people seem to gravitate toward moment.js.

    Borrowing from this answer, you could do something like this (i.e. use a convert function that creates the date with the UTC constructor) without moment.js:

    controller

    var app1 = angular.module('app1',[]);
    
    app1.controller('ctrl',['$scope',function($scope){
    
      var toUTCDate = function(date){
        var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
        return _utc;
      };
    
      var millisToUTCDate = function(millis){
        return toUTCDate(new Date(millis));
      };
    
        $scope.toUTCDate = toUTCDate;
        $scope.millisToUTCDate = millisToUTCDate;
    
      }]);
    

    template

    
    
      
        
        
        
      
    
      
        
    utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
    local {{1400167800 | date:'dd-M-yyyy H:mm'}}

    here's plunker to play with it

    See also this and this.

    Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.

提交回复
热议问题