convert UTC to local time using angularjs

前端 未结 4 2032
梦谈多话
梦谈多话 2020-12-16 01:08

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

{{trans.txnDate}}         


        
4条回答
  •  心在旅途
    2020-12-16 01:47

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

提交回复
热议问题