使用angularjs将UTC转换为本地时间

cha*_*dru 9 angularjs

作为json的回复,我得到了UTC时区.我需要将它转换为当地时间.

<span class="text-muted">{{trans.txnDate}}</span>
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙吗???

谢谢..

Jas*_*son 26

我只需要解决这个问题以及来自.NET Web API的日期,格式为'yyyy-MM-ddTHH:mm:ss'(例如2016-02-23T00:11:31),没有'Z'后缀表示UTC时间.

我创建了这个扩展角度日期过滤器的过滤器,并确保UTC时间包含时区后缀.

UTC到本地过滤器:

(function () {
    'use strict';

    angular
        .module('app')
        .filter('utcToLocal', utcToLocal);

    function utcToLocal($filter) {
        return function (utcDateString, format) {
            if (!utcDateString) {
                return;
            }

            // append 'Z' to the date string to indicate UTC time if the timezone isn't already specified
            if (utcDateString.indexOf('Z') === -1 && utcDateString.indexOf('+') === -1) {
                utcDateString += 'Z';
            }

            return $filter('date')(utcDateString, format);
        };
    }
})();
Run Code Online (Sandbox Code Playgroud)

用法示例:

{{product.CreatedDate | utcToLocal:"dd.MM.yyyy"}}
Run Code Online (Sandbox Code Playgroud)


Rah*_*sai 10

编辑(2017年1月2日):请参考@Jason的答案,它比这个更好,因为它使用自定义过滤器来修复日期格式 - 这是更加Angular的方式.


我的原始答案和编辑:

您可以使用date过滤器格式化日期:

<span class="text-muted">{{trans.txnDate | date:'yyyy-MM-dd HH:mm:ss Z' }}</span>
Run Code Online (Sandbox Code Playgroud)

这将输出:

2010-10-29 09:10:23 +0530
Run Code Online (Sandbox Code Playgroud)

(假设trans.txnDate = 1288323623006;)

请参阅dateangularjs.org中的此文档.它有很多非常有用的例子!


编辑:

在回复您的评论时,请使用以下内容将日期视为17 oct 2014:

<span class="text-muted">{{trans.txnDate | date:'dd MMM yyyy' | lowercase }}</span>
Run Code Online (Sandbox Code Playgroud)

查看我上面提到的文档链接.

EDIT2:

在回复您的其他评论时,请使用以下代码.问题是您获取的字符串格式不正确,因此Date对象无法识别它.我已在控制器中格式化它,然后传递给视图.

function MyCtrl($scope) {
  var dateString = "2014:10:17T18:30:00Z";
  dateString = dateString.replace(/:/, '-'); // replaces first ":" character
  dateString = dateString.replace(/:/, '-'); // replaces second ":" character
  $scope.date = new Date(dateString);
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="MyCtrl">
  {{date | date:'dd MMM yyyy' | lowercase }}
</div>
Run Code Online (Sandbox Code Playgroud)

可以通过找到更换前两个:字符的更智能方法来改进替换的JS代码.