Published: March 31 2016

AngularJS - UTC to Local Date Time Filter

I ran into an issue recently with converting UTC dates into local dates for display in an AngularJS application. ASP.NET Web API was being used as the back end and returning dates in the format 'yyyy-MM-ddTHH:mm:ss' (e.g. 2016-03-31T00:11:31).

After a bit of digging around I found that the date needs to have a 'Z' on the end to indicate that it's UTC time (for detailed info check out the ISO 8601 format on wikipedia).

It turns out the angular date filter automatically converts UTC to local time if the date is correctly formatted (with a 'Z' suffix).

To fix the issue I created a simple filter that wraps the angular date filter and ensures that the input date has a trailing 'Z' before converting and formatting.
 

AngularJS Convert UTC to Local Filter

(function () {
    'use strict';

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

    function Filter($filter) {
        return function (utcDateString, format) {
            // return if input date is null or undefined
            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';
            }

            // convert and format date using the built in angularjs date filter
            return $filter('date')(utcDateString, format);
        };
    }
})();


Example usage of UTC to Local Time Filter

<span>Local date & time converted from UTC: {{vm.myUtcDate | utcToLocal:'dd.MM.yy - hh.mm a'}}</span>

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some AngularJS Help?

Search fiverr to find help quickly from experienced AngularJS developers.



Supported by