Date Time Interval Javascript Extensions
////////////////////////// // BEGIN: Interval class ////////////////////////// // Constructor // (establishes instance data) function Interval(dayOrMs, h, m, s) { if (dayOrMs === undefined) this.ms = 0; else if (h === undefined) this.ms = dayOrMs else this.ms = (1000*s) + (60000*m) + (3600000*h) + (86400000*dayOrMs); this.timeoutHandler = null; this.countdownExpiry = null; } Interval.prototype.toString = function () { var retStr = ""; var days = Math.floor(this.ms / 86400000); var rem = this.ms - (days * 86400000); var h = Math.floor(rem / 3600000); rem -= (h * 3600000); var m = Math.floor(rem / 60000); rem -= (m * 60000); var s = Math.floor(rem / 1000); if (days) retStr += String(days) + " d "; retStr += (new String(h)).pad(2, '0') + ":" + (new String(m)).pad(2, '0') + ":" + (new String(s)).pad(2, '0'); return retStr; } Interval.prototype.startCountdown = function (cb) { if (this.timeoutHandler) clearTimeout(this.timeoutHandler); this.countdownExpiry = new Date(Date.now() + this.ms); this.timeoutHandler = setTimeout(cb, this.ms); } Interval.prototype.countdownRemaining = function () { var retval = new Interval(); if (this.countdownExpiry) { if (this.countdownExpiry.timeUntil().ms) retval = this.countdownExpiry.timeUntil(); } return retval; } Interval.prototype.cancelCountdown = function () { if (this.timeoutHandler) clearTimeout(this.timeoutHandler); } //////////////////////// // END: Interval class //////////////////////// /////////////////////////// // Date class extensions /////////////////////////// // Add timeSince and timeUntil functions to Date class Date.prototype.timeSince = function () { var now = new Date(); if ((now - this) > 0) return new Interval(now - this); else return new Interval(); } Date.prototype.timeUntil = function () { var now = new Date(); if ((this - now) > 0) return new Interval(this - now); else return new Interval(); } // Return a date set to midnight of this date Date.prototype.midnight = function () { return new Date(this.getFullYear(), this.getMonth(), this.getDate()); } // Add addInterval and subtractInterval functions to Date class Date.prototype.addInterval = function (i) { if (i instanceof Interval) this.setTime(this.getTime() + i.ms); } Date.prototype.subtractInterval = function (i) { if (i instanceof Interval) this.setTime(this.getTime() - i.ms); }
page revision: 2, last edited: 07 Sep 2014 02:47