AngularJS $http date parsing
Adds a response interceptor to $httpProvider that converts ISO 8601 date strings into Date objects.
HTML
<div ng-app="app" ng-controller="DemoController">
<form ng-submit="go()">
<label for="url-input">String returned from server</label>
<input type="text" id="url-input" ng-model="form.url" value="lazio.coni.it/lazio/lazio/ricerca-societ%C3%A0-sportive.html?pagina=1" />
<button type="submit">Go</button>
</form>
<div ng-show="url">
<p><code>response.data.url instanceof String === {{isUrl}}</code>
</p>
<p ng-show="isUrl">Display using Angular's date filter: {{url}}</p>
</div>
</div>
JavaScript
// Define our application module.
var app = angular.module("app", []);
// Configure the $httpProvider by adding our date transformer
app.config(["$httpProvider", function ($httpProvider) {
$httpProvider.defaults.transformResponse.push(function(responseData){
convertDateStringsToDates(responseData);
return responseData;
});
}]);
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 convertDateStringsToDates(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.
// TODO: Improve this regex to better match ISO 8601 date strings.
if (typeof value === "string" && (match = value.match(regexIso8601))) {
// Assume that Date.parse can parse ISO 8601 strings, or has been shimmed in older browsers to do so.
var milliseconds = Date.parse(match[0]);
if (!isNaN(milliseconds)) {
input[key] = new Date(milliseconds);
}
} else if (typeof value === "object") {
// Recurse into object
convertDateStringsToDates(value);
}
}
}
app.controller("DemoController", ["$http", "$scope", DemoController]);
function DemoController($http, $scope) {
$scope.form = {
url: "lazio.coni.it/lazio/lazio/ricerca-societ%C3%A0-sportive.html?pagina=1"
};
$scope.go = function () {
var request = queryServer($http, $scope.form);
request.then(function (response) {
$scope.isUrl = response.data.url;
$scope.url = response.data.url;
$http({ method: 'GET', url: $scope.url})
.success(function
(data) {
$scope.url = data;...