import Strings from '@pilotlab/strings'; export class TimeSpan { constructor ( milliseconds:number = 0, seconds:number = 0, minutes:number = 0, hours:number = 0, days:number = 0 ) { this._millis = (days * 86400 + hours * 3600 + minutes * 60 + seconds) * 1000 + milliseconds; } private _millis:number = 0; private _rounder(value:number):number { if(this._millis < 0) return Math.ceil(value); return Math.floor(value); } static unitsInMilliseconds:any = { millisecond: 1, centisecond: 10, decisecond: 100, second: 1000, minute: 60000, hour: 3600000, day: 86400000 }; add(timespan:TimeSpan):TimeSpan { return new TimeSpan(timespan._millis + this._millis); } subtract(timespan:TimeSpan):TimeSpan { return new TimeSpan(this._millis - timespan._millis); } negate() { this._millis *= -1; } compare(timespan:TimeSpan):number { if(this._millis > timespan._millis) return 1; if(this._millis == timespan._millis) return 0; if(this._millis < timespan._millis) return -1; return 0; } get duration():TimeSpan { return new TimeSpan(Math.abs(this._millis)); } get days():number { return this._rounder(this._millis / (24 * 3600 * 1000) ); } get hours():number { return this._rounder( (this._millis % (24 * 3600 * 1000)) / (3600 * 1000)); } get minutes():number { return this._rounder( (this._millis % (3600 * 1000)) / (60 * 1000)); } get seconds():number { return this._rounder((this._millis % 60000) / 1000); } get milliseconds():number { return this._rounder(this._millis % 1000); } get daysTotal():number { return this._millis / (24 * 3600 * 1000); } get hoursTotal():number { return this._millis / (3600 * 1000); } get minutesTotal():number { return this._millis / (60 * 1000); } get secondsTotal():number { return this._millis / 1000; } get millisecondsTotal() { return this._millis; } toString():string { let formatted = (this._millis < 0 ? '-' : '') + (Math.abs(this.days) ? Strings.padDigits(Math.abs(this.days), 2) + '.': '') + Strings.padDigits(Math.abs(this.hours), 2) + ':' + Strings.padDigits(Math.abs(this.minutes), 2) + ':' + Strings.padDigits(Math.abs(this.seconds), 2) + '.' + Strings.padDigits(Math.abs(this.milliseconds), 3); return formatted; } } // End class export default TimeSpan;