Last active
July 27, 2021 01:19
-
-
Save mmyoji/e6965fd0a464667ab55e4f0b39132517 to your computer and use it in GitHub Desktop.
Get Date diff (sec, min, hours) like moment.diff with Vanilla JS
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
const SECONDS = 1000; | |
const MINUTES = SECONDS * 60; | |
const HOURS = MINUTES * 60; | |
interface Result { | |
hours: number; | |
minutes: number; | |
seconds: number; | |
} | |
function dateDiff(d1: Date, d2: Date): Result { | |
const diff = Math.abs(Number(d1) - Number(d2)); | |
const hours = Math.floor(diff / HOURS); | |
const minutes = Math.floor((diff - hours * HOURS) / MINUTES); | |
const seconds = Math.floor( | |
(diff - (hours * HOURS + minutes * MINUTES)) / SECONDS | |
); | |
return { | |
seconds, | |
minutes, | |
hours, | |
}; | |
} | |
// Test | |
const TEST_DATA = [ | |
{ | |
d1: new Date("2020-01-02T10:00:00"), | |
d2: new Date("2020-01-02T10:00:30"), | |
results: { seconds: 30, minutes: 0, hours: 0 }, | |
}, | |
{ | |
d1: new Date("2020-01-02T10:00:00"), | |
d2: new Date("2020-01-02T10:10:30"), | |
results: { seconds: 30, minutes: 10, hours: 0 }, | |
}, | |
{ | |
d1: new Date("2020-01-02T10:00:00"), | |
d2: new Date("2020-01-02T12:00:30"), | |
results: { seconds: 30, minutes: 0, hours: 2 }, | |
}, | |
{ | |
d1: new Date("2020-01-02T10:00:00"), | |
d2: new Date("2020-01-03T10:00:00"), | |
results: { seconds: 0, minutes: 0, hours: 24 }, | |
}, | |
{ | |
d1: new Date("2020-01-02T10:00:00"), | |
d2: new Date("2020-01-03T11:20:10"), | |
results: { seconds: 10, minutes: 20, hours: 25 }, | |
}, | |
{ | |
d1: new Date("2020-01-02T10:00:00"), | |
d2: new Date("2020-01-03T10:01:22"), | |
results: { seconds: 22, minutes: 1, hours: 24 }, | |
}, | |
]; | |
function assertResult(actual: Result, expected: Result): boolean { | |
return ( | |
actual.seconds === expected.seconds && | |
actual.minutes === expected.minutes && | |
actual.hours === expected.hours | |
); | |
} | |
let i = 0; | |
for (const { d1, d2, results } of TEST_DATA) { | |
const ret = dateDiff(d1, d2); | |
if (assertResult(ret, results)) { | |
console.log(`SUCCESS: ${i}`); | |
} else { | |
console.error( | |
`FAILED: ${i}, seconds=${ret.seconds}, minutes=${ret.minutes}, hours=${ret.hours}` | |
); | |
} | |
i++; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment