Created
July 3, 2014 07:23
-
-
Save ScottGuymer/9994dae637bb2055d58b to your computer and use it in GitHub Desktop.
Angular interceptor to reformat ISO 8601 strings into Javascript date objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('dateInterceptor',[]) | |
.config(['$httpProvider', function ($httpProvider) { | |
var regexIso8601 = /^(\d{4}|\+\d{6})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})\.(\d{1,})(Z|([\-+])(\d{2}):(\d{2}))?)?)?)?$/; | |
// function to parse through response json and replace ISO8601 date strings with date objects | |
var convertDateStringsToDates = function(input) { | |
// Ignore things that aren't objects. | |
if (typeof input !== "object") return input; | |
for (var key in input) { | |
if (!input.hasOwnProperty(key)) continue; | |
var value = input[key]; | |
var match; | |
// Check for string properties which look like dates. | |
if (typeof value === "string" && (match = value.match(regexIso8601))) { | |
var milliseconds = Date.parse(match[0]) | |
if (!isNaN(milliseconds)) { | |
input[key] = new Date(milliseconds); | |
} | |
} else if (typeof value === "object") { | |
// Recurse into object | |
convertDateStringsToDates(value); | |
} | |
} | |
}; | |
// push the transform into the transform array | |
$httpProvider.defaults.transformResponse.push(function(responseData){ | |
convertDateStringsToDates(responseData); | |
return responseData; | |
}); | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Beware that this regex doesn't match all ISO8601 date strings. We've switched to using the regex from over here