Using AngularJS date filter with UTC date

后端 未结 10 2279
無奈伤痛
無奈伤痛 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 07:58

    An evolved version of ossek solution

    Custom filter is more appropriate, then you can use it anywhere in the project

    js file

    var myApp = angular.module('myApp',[]);
    
    myApp.filter('utcdate', ['$filter','$locale', function($filter, $locale){
    
        return function (input, format) {
            if (!angular.isDefined(format)) {
                format = $locale['DATETIME_FORMATS']['medium'];
            }
    
            var date = new Date(input);
            var d = new Date()
            var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
            return $filter('date')(_utc, format)
        };
    
     }]);
    

    in template

    This will convert UTC time to local time

    {{dateTimeInUTC | utcdate :'MMM d, y h:mm:ss a'}}

提交回复
热议问题