使用带有 UTC 日期的 AngularJS 日期过滤器 [英] Using AngularJS date filter with UTC date
问题描述
我有一个以毫秒为单位的 UTC 日期,我将其传递给 Angular 的日期过滤器以进行人工格式化.
{{someDate |日期:'d MMMM yyyy'}}
很棒,除了 someDate
是 UTC 并且日期过滤器认为它是本地时间.
如何告诉 Angular someDate
是 UTC?
谢谢.
类似问题 这里
我将重新发布我的回复并提议合并:
输出 UTC 似乎有些混乱——人们似乎倾向于 moment.js.
借用这个答案,你可以在没有 moment.js 的情况下做这样的事情(即使用一个使用 UTC 构造函数创建日期的转换函数):
控制器
var app1 = angular.module('app1',[]);app1.controller('ctrl',['$scope',function($scope){var toUTCDate = 函数(日期){var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());返回_utc;};var millisToUTCDate = function(millis){返回到UTCDate(新日期(毫秒));};$scope.toUTCDate = toUTCDate;$scope.millisToUTCDate = millisToUTCDate;}]);
模板
<头><script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script><link rel="stylesheet" href="style.css"/><script src="script.js"></script>头部><身体><div ng-controller="ctrl"><div>UTC {{millisToUTCDate(1400167800) |日期:'dd-M-yyyy H:mm'}}
<div>本地 {{1400167800 |日期:'dd-M-yyyy H:mm'}}
</html>
这里是 plunker 玩它
另请注意,使用此方法,如果您使用 Angular 日期过滤器中的Z",它似乎仍会打印您的本地时区偏移量.
I have an UTC date in milliseconds which I am passing to Angular's date filter for human formatting.
{{someDate | date:'d MMMM yyyy'}}
Awesome, except someDate
is in UTC and the date filter considers it to be in local time.
How can I tell Angular that someDate
is UTC?
Thank you.
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
<html ng-app="app1">
<head>
<script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ctrl">
<div>
utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
</div>
<div>
local {{1400167800 | date:'dd-M-yyyy H:mm'}}
</div>
</div>
</body>
</html>
here's plunker to play with it
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.
这篇关于使用带有 UTC 日期的 AngularJS 日期过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!