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>
Need Some AngularJS Help?
Search fiverr for freelance AngularJS developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!