Skip to content

Instantly share code, notes, and snippets.

@ScottGuymer
Created July 3, 2014 07:23
Show Gist options
  • Save ScottGuymer/9994dae637bb2055d58b to your computer and use it in GitHub Desktop.
Save ScottGuymer/9994dae637bb2055d58b to your computer and use it in GitHub Desktop.
Angular interceptor to reformat ISO 8601 strings into Javascript date objects
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;
});
}]);
@fastf0rward
Copy link

Beware that this regex doesn't match all ISO8601 date strings. We've switched to using the regex from over here

^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$ - See more at: http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/#sthash.n4QweZIl.dpuf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment