AngularJS日期过滤器添加了意外的时区偏移量? [英] AngularJS date filter is adding unexpected timezone offset?
问题描述
文档: https://docs.angularjs.org/api/ng/filter / date
柱塞: https://plnkr.co/edit/q6KPNejv52SzewDlvGyu?p=preview
以下代码段:
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>
- 否时区-将
01
显示为小时。 - 通过
UTC
作为时区-显示12
作为小时。
- No timezone - displays
01
as hour. - Passing
UTC
as timezone - displays12
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?
(也许我应该只用片刻,束的大小在这里没有多大关系)
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;
};
不是解决方案: AngularJS全局日期时区偏移(将GMT设置为默认值仍显示为12小时)
Not a solution: AngularJS global Date timezone offset (setting GMT as default still displays it as 12 hours)
可能的重复项: AngularJs过滤日期增加了2小时(未回答)
Potential duplicate: AngularJs filter date adding 2 hours (not answered)
推荐答案
使用 date:'HH:mm:ss:sss':' UTC'
使用国会大厦HH:
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':一天中的小时,填充(00-23)
- 'H':一天中的小时(0-23)
- 'hh':以AM / PM表示的小时,已填充(01-12)
- 'h':AM / PM中的小时,(1-12)
- '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)
有关更多信息,请参见
- AngularJS
date
Filter API Reference
这篇关于AngularJS日期过滤器添加了意外的时区偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!