使用AngularJS日期过滤器,UTC日期 [英] Using AngularJS date filter with UTC date

查看:315
本文介绍了使用AngularJS日期过滤器,UTC日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这,我传给角的日期过滤器对人类格式毫秒的UTC日期。

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

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

真棒,除了 someDate 是UTC和日期过滤器认为它是本地时间。

Awesome, except someDate is in UTC and the date filter considers it to be in local time.

我如何才能知道那角 someDate 是UTC?

How can I tell Angular that someDate is UTC?

感谢您。

推荐答案

类似的问题<一href=\"http://stackoverflow.com/questions/21782893/angular-date-filter-adds-timezone-how-to-output-utc/21785453#21785453\">here

我会重新发布我的回应,并提出合并:

I'll repost my response and propose a merge:

输出UTC似乎有些混乱的主题 - 人似乎倾向于 moment.js

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

借款<一个href=\"http://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc#answer-6777470\">answer,你可以做这样的事情(即使用创建与UTC构造日期转换功能)无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:

控制器

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;

  }]);

模板

<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>

下面的 plunker 发挥它

又见<一个href=\"http://stackoverflow.com/questions/20662140/using-angularjs-date-filter-with-utc-date?lq=1\">this和<一个href=\"http://stackoverflow.com/questions/20470139/angularjs-timestamp-to-formatted-utc-time-with-date-helper\">this.

另外请注意,使用这种方法,如果您从角的日期过滤器中使用的'Z',现在看来,这仍然会打印您的本地时区的偏移量。

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.

这篇关于使用AngularJS日期过滤器,UTC日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆