import * as angular from "angular"; export class DocumentService { static $inject = ['dateFilter']; constructor(private dateFilter: any) { } public parseResponseDates(response: any) { this.parseDates(response); return response; } public formatRequestDates(request: any, hasTime?: any) { let result: any = angular.copy(request); this.formatDates(result, hasTime); return angular.toJson(result); } private formatDate(date: Date): string { return this.dateFilter(date, 'yyyy-MM-dd'); } private formatDateTime(date: Date): string { return this.dateFilter(date, 'yyyy-MM-ddTHH:mm:ss'); } private formatDates(input: any, hasTime?: any) { for (let key in input) { if (!input.hasOwnProperty(key)) continue; if (angular.isDate(input[key])) { let date: Date = input[key]; if (hasTime && hasTime[key]) { input[key] = this.formatDateTime(date); } else { input[key] = this.formatDate(date); } } else if (typeof input[key] === "object") { this.formatDates(input[key], hasTime); } } } private parseDates(input: any) { for (let key in input) { if (!input.hasOwnProperty(key)) continue; if (typeof input[key] === "object") { this.parseDates(input[key]); } else { let match = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*$/.exec(input[key]); if (typeof input[key] === "string" && match) { input[key] = new Date(input[key]); } match = /^\d{4}-\d{2}-\d{2}$/.exec(input[key]); if (typeof input[key] === "string" && match) { let date = new Date(input[key]); date.setHours(0); input[key] = date; } } } } }