mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1const NOW = 5
2const MINUTE = 60
3const HOUR = MINUTE * 60
4const DAY = HOUR * 24
5const MONTH_30 = DAY * 30
6const MONTH = DAY * 30.41675 // This results in 365.001 days in a year, which is close enough for nearly all cases
7export function ago(date: number | string | Date): string {
8 let ts: number
9 if (typeof date === 'string') {
10 ts = Number(new Date(date))
11 } else if (date instanceof Date) {
12 ts = Number(date)
13 } else {
14 ts = date
15 }
16 const diffSeconds = Math.floor((Date.now() - ts) / 1e3)
17 if (diffSeconds < NOW) {
18 return `now`
19 } else if (diffSeconds < MINUTE) {
20 return `${diffSeconds}s`
21 } else if (diffSeconds < HOUR) {
22 return `${Math.floor(diffSeconds / MINUTE)}m`
23 } else if (diffSeconds < DAY) {
24 return `${Math.floor(diffSeconds / HOUR)}h`
25 } else if (diffSeconds < MONTH_30) {
26 return `${Math.round(diffSeconds / DAY)}d`
27 } else {
28 let months = diffSeconds / MONTH
29 if (months % 1 >= 0.9) {
30 months = Math.ceil(months)
31 } else {
32 months = Math.floor(months)
33 }
34
35 if (months < 12) {
36 return `${months}mo`
37 } else {
38 return new Date(ts).toLocaleDateString()
39 }
40 }
41}
42
43export function niceDate(date: number | string | Date) {
44 const d = new Date(date)
45 return `${d.toLocaleDateString('en-us', {
46 year: 'numeric',
47 month: 'short',
48 day: 'numeric',
49 })} at ${d.toLocaleTimeString(undefined, {
50 hour: 'numeric',
51 minute: '2-digit',
52 })}`
53}
54
55export function getAge(birthDate: Date): number {
56 var today = new Date()
57 var age = today.getFullYear() - birthDate.getFullYear()
58 var m = today.getMonth() - birthDate.getMonth()
59 if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
60 age--
61 }
62 return age
63}