Skip to content

Commit 74ead62

Browse files
authored
Merge pull request #6 from Yugveer06/main
Add Relative Time Formatter Utility Function
2 parents 71edbd6 + 5b07e3c commit 74ead62

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

public/data/javascript.json

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,41 @@
114114
],
115115
"tags": ["javascript", "date", "time-difference", "utility"],
116116
"author": "technoph1le"
117+
},
118+
{
119+
"title": "Relative Time Formatter",
120+
"description": "Displays how long ago a date occurred or how far in the future a date is.",
121+
"code": [
122+
"const getRelativeTime = (date) => {",
123+
" const now = Date.now();",
124+
" const diff = date.getTime() - now;",
125+
" const seconds = Math.abs(Math.floor(diff / 1000));",
126+
" const minutes = Math.abs(Math.floor(seconds / 60));",
127+
" const hours = Math.abs(Math.floor(minutes / 60));",
128+
" const days = Math.abs(Math.floor(hours / 24));",
129+
" const years = Math.abs(Math.floor(days / 365));",
130+
"",
131+
" if (Math.abs(diff) < 1000) return 'just now';",
132+
"",
133+
" const isFuture = diff > 0;",
134+
"",
135+
" if (years > 0) return `${isFuture ? 'in ' : ''}${years} ${years === 1 ? 'year' : 'years'}${isFuture ? '' : ' ago'}`;",
136+
" if (days > 0) return `${isFuture ? 'in ' : ''}${days} ${days === 1 ? 'day' : 'days'}${isFuture ? '' : ' ago'}`;",
137+
" if (hours > 0) return `${isFuture ? 'in ' : ''}${hours} ${hours === 1 ? 'hour' : 'hours'}${isFuture ? '' : ' ago'}`;",
138+
" if (minutes > 0) return `${isFuture ? 'in ' : ''}${minutes} ${minutes === 1 ? 'minute' : 'minutes'}${isFuture ? '' : ' ago'}`;",
139+
"",
140+
" return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`;",
141+
"}",
142+
"",
143+
"// usage",
144+
"const pastDate = new Date('2021-12-29 13:00:00');",
145+
"const futureDate = new Date('2026-12-29 13:00:00');",
146+
"console.log(timeAgoOrAhead(pastDate)); // x years ago",
147+
"console.log(timeAgoOrAhead(new Date())); // just now",
148+
"console.log(timeAgoOrAhead(futureDate)); // in x years"
149+
],
150+
"tags": ["javascript", "date", "time", "relative", "future", "past", "utility"],
151+
"author": "Yugveer06"
117152
}
118153
]
119154
},

0 commit comments

Comments
 (0)