AngularJS date filter is adding unexpected timezon

2020-05-02 05:02发布

问题:

Docs: https://docs.angularjs.org/api/ng/filter/date

Plunker: https://plnkr.co/edit/q6KPNejv52SzewDlvGyu?p=preview

Code snippet below:

var app = angular.module("app", []);

app.controller("ctrl", function($scope, $interval) {
    $scope.message = "It works!";
    $scope.dateStart = new Date();
    
    $interval(function() {
      $scope.dateNow = new Date();
    }, 42)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
    {{ message }} <br>
    
    {{ dateNow - dateStart | date: 'hh:mm:ss:sss' }} <br>
    
    {{ dateNow - dateStart | date: 'hh:mm:ss:sss' : 'UTC' }} <br>
    
</div>

  • No timezone - displays 01 as hour.
  • Passing UTC as timezone - displays 12 as hour.

In my other project I figured this workaround... It feels crap, I don't want to copy-paste crap code. Surely there is a better way?

(maybe I should just use moment, bundle size does not matter that much here)

app.filter('mydate', function(){
  return function(text, extra) {
    // https://stackoverflow.com/a/39209842/775359
    var date = new Date(text)
    var userTimezoneOffset = date.getTimezoneOffset() * 60000;
    var newdate = new Date(date.getTime() + userTimezoneOffset);

    return pad(newdate.getHours(),2) + ":" + pad(newdate.getMinutes(),2) + ":" + pad(newdate.getSeconds(),2) 
           + (extra ? ":" + pad(newdate.getMilliseconds(), 3) : "");
  };
});

app.filter('pad', [function(){
  return function(text, width) { 
    return pad(text, width)
  };
}]);

function pad(text, width) { 
  text = text + ''; // converting to string because if we pass number it will fail
  return text.length >= width ? text : new Array(width - text.length + 1).join('0') + text;
};

Not a solution: AngularJS global Date timezone offset (setting GMT as default still displays it as 12 hours)

Potential duplicate: AngularJs filter date adding 2 hours (not answered)

回答1:

Use date: 'HH:mm:ss:sss' : 'UTC' Using capitol HH:

var app = angular.module("app", []);

app.controller("ctrl", function($scope, $interval) {
    $scope.message = "It works!";
    $scope.dateStart = new Date().valueOf();
    
    $interval(function() {
      $scope.dateNow = new Date().valueOf();
    }, 42)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
    {{ message }} <br>
    
    {{ dateNow - dateStart | date: 'HH:mm:ss:sss' : 'UTC' }} <br>
    
</div>

The format string can be composed of the following elements:

  • 'HH': Hour in day, padded (00-23)
  • 'H': Hour in day (0-23)
  • 'hh': Hour in AM/PM, padded (01-12)
  • 'h': Hour in AM/PM, (1-12)

For more information, see

  • AngularJS date Filter API Reference