forked from WorldBrain/Memex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnice-time.js
69 lines (66 loc) · 1.81 KB
/
nice-time.js
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function hourString(date) {
// return date.toLocaleTimeString([], {hour: 'numeric', minute: '2-digit'})
return `${('0' + date.getHours()).slice(-2)}:${(
'0' + date.getMinutes()
).slice(-2)}`
}
function dayString(date) {
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
return days[date.getDay()]
}
function monthString(date) {
const months = [
'Jan',
'Feb',
'March',
'Apr',
'May',
'June',
'July',
'Aug',
'Sept',
'Oct',
'Nov',
'Dec',
]
return months[date.getMonth()]
}
// Get something nicely readable - at least to my personal taste.
export default function niceTime(date, { now = undefined } = {}) {
const then = new Date(date)
now = now || new Date()
const secondsAgo = (now - then) / 1000
if (secondsAgo < -60 * 60 * 24) {
return 'in the future?!'
}
if (secondsAgo < -60) {
return 'soon?!'
}
if (secondsAgo < 90) {
return 'now'
}
if (secondsAgo < 60 * 10) {
return `${Math.round(secondsAgo / 60)} minutes ago`
}
if (secondsAgo < 60 * 60) {
return `${Math.round(secondsAgo / 60 / 5) * 5} minutes ago`
}
if (
secondsAgo < 60 * 60 * 24 &&
(now.getDay() === then.getDay() || secondsAgo < 60 * 60 * 6)
) {
return `Today ${hourString(then)}`
}
if (secondsAgo < 60 * 60 * 24) {
return `Yesterday ${hourString(then)}`
}
if (secondsAgo < 60 * 60 * 24 * 3) {
return `${dayString(then)} ${hourString(then)}`
}
if (then.getYear() === now.getYear()) {
return `${then.getDate()} ${monthString(then)} ${hourString(then)}`
}
return `${then.getDate()} ${monthString(
then,
)} ${then.getFullYear()} ${hourString(then)}`
}