-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdate-utils.ts
More file actions
47 lines (43 loc) · 1.65 KB
/
Copy pathdate-utils.ts
File metadata and controls
47 lines (43 loc) · 1.65 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Date utility functions.
*/
/**
* Format a date as a human-readable relative string.
* e.g. "2 days ago", "just now", "in 3 hours"
*/
export function formatRelative(date: Date, now: Date = new Date()): string {
const diffMs = now.getTime() - date.getTime()
const diffSec = diffMs / 1000
const diffMin = diffSec / 60
const diffHours = diffMin / 60
// Round the magnitude, not the signed value: Math.round breaks .5 ties toward
// +Infinity, so rounding a negative diff would make past/future asymmetric
// (Math.round(-1.5) === -1 but Math.round(1.5) === 2). Sign is used only to
// choose the "ago" vs "in" direction below.
const diffDays = Math.round(Math.abs(diffHours) / 24)
if (Math.abs(diffSec) < 60) return "just now"
if (Math.abs(diffMin) < 60) {
const m = Math.round(Math.abs(diffMin))
return diffMs > 0 ? `${m} minute${m !== 1 ? "s" : ""} ago` : `in ${m} minute${m !== 1 ? "s" : ""}`
}
if (Math.abs(diffHours) < 24) {
const h = Math.round(Math.abs(diffHours))
return diffMs > 0 ? `${h} hour${h !== 1 ? "s" : ""} ago` : `in ${h} hour${h !== 1 ? "s" : ""}`
}
const d = diffDays
return diffMs > 0 ? `${d} day${d !== 1 ? "s" : ""} ago` : `in ${d} day${d !== 1 ? "s" : ""}`
}
/**
* Returns true if two dates fall on the same calendar day.
*/
export function isSameDay(a: Date, b: Date): boolean {
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
}
/**
* Add a number of days to a date (returns a new Date).
*/
export function addDays(date: Date, days: number): Date {
const result = new Date(date)
result.setDate(result.getDate() + days)
return result
}