-
-
Save DavidMsnap/6c267618eda11997f656d4a17bf72def to your computer and use it in GitHub Desktop.
JavaScript: DateDiff & DateMeasure: Calculate days, hours, minutes, seconds between two Dates with es6 classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DateMeasure { | |
constructor(ms) { | |
const negativeMS = ms < 0; | |
let d, h, m, s; | |
// this change is needed for it to work with | |
// date1 before date2 diffs | |
if (negativeMS) { | |
ms *= -1; | |
} | |
s = Math.floor(ms / 1000); | |
m = Math.floor(s / 60); | |
s = s % 60; | |
h = Math.floor(m / 60); | |
m = m % 60; | |
d = Math.floor(h / 24); | |
h = h % 24; | |
// this change is needed for it to work with | |
// date1 before date2 diffs | |
if (negativeMS) { | |
d *= -1; | |
h *= -1; | |
m *= -1; | |
s *= -1; | |
} | |
this.days = d; | |
this.hours = h; | |
this.minutes = m; | |
this.seconds = s; | |
}; | |
} | |
class DateDiff { | |
constructor(date1, date2) { | |
this.days = null; | |
this.hours = null; | |
this.minutes = null; | |
this.seconds = null; | |
this.date1 = date1; | |
this.date2 = date2; | |
this.init(); | |
} | |
init() { | |
let differenceMS = this.date1 - this.date2; | |
let data = new DateMeasure(differenceMS, false); | |
this.days = data.days; | |
this.hours = data.hours; | |
this.minutes = data.minutes; | |
this.seconds = data.seconds; | |
}; | |
} | |
// not very useful since have to input date1 again | |
Date.diff = function(date1, date2) { | |
return new DateDiff(date1, date2); | |
}; | |
// get difference of date to another date2 | |
Date.prototype.diff = function(date2) { | |
return new DateDiff(this, date2); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment