Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

convert UTC to local time using angularjs

As a response from the json I am getting the UTC timezone. I need to convert it to local time.

<span class="text-muted">{{trans.txnDate}}</span>

Can anyone help on this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I just had to solve this problem as well with dates coming from .NET Web API in the format 'yyyy-MM-ddTHH:mm:ss' (e.g. 2016-02-23T00:11:31) without the 'Z' suffix to indicate UTC time.

I created this filter that extends the angular date filter and ensures that the timezone suffix is included for UTC time.

UTC to Local Filter:

(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);
        };
    }
})();

Example Usage:

{{product.CreatedDate | utcToLocal:"dd.MM.yyyy"}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...