-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime.ts
More file actions
33 lines (28 loc) · 808 Bytes
/
time.ts
File metadata and controls
33 lines (28 loc) · 808 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Gets difference in given unit between two given dates (order of the dates don't matter)
* @param date1 first date
* @param date2 second date
* @param unit unit of time difference
* @returns time difference (float number)
*/
export const getTimeDifference = (
date1: Date,
date2: Date,
unit: "days" | "hours" | "minutes" | "seconds"
): number => {
const differenceInSeconds =
Math.abs(date1.getTime() - date2.getTime()) / 1000;
if (unit === "seconds") {
return differenceInSeconds;
}
if (unit === "minutes") {
return differenceInSeconds / 60;
}
if (unit === "hours") {
return differenceInSeconds / (60 * 60);
}
if (unit === "days") {
return differenceInSeconds / (60 * 60 * 24);
}
throw new Error(`getTimeDifference: invalid unit (${unit})`);
};