Skip to content

Commit

Permalink
Merge pull request dostonnabotov#6 from Yugveer06/main
Browse files Browse the repository at this point in the history
Add Relative Time Formatter Utility Function
  • Loading branch information
dostonnabotov authored Dec 29, 2024
2 parents 71edbd6 + 5b07e3c commit 74ead62
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions public/data/javascript.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,41 @@
],
"tags": ["javascript", "date", "time-difference", "utility"],
"author": "technoph1le"
},
{
"title": "Relative Time Formatter",
"description": "Displays how long ago a date occurred or how far in the future a date is.",
"code": [
"const getRelativeTime = (date) => {",
" const now = Date.now();",
" const diff = date.getTime() - now;",
" const seconds = Math.abs(Math.floor(diff / 1000));",
" const minutes = Math.abs(Math.floor(seconds / 60));",
" const hours = Math.abs(Math.floor(minutes / 60));",
" const days = Math.abs(Math.floor(hours / 24));",
" const years = Math.abs(Math.floor(days / 365));",
"",
" if (Math.abs(diff) < 1000) return 'just now';",
"",
" const isFuture = diff > 0;",
"",
" if (years > 0) return `${isFuture ? 'in ' : ''}${years} ${years === 1 ? 'year' : 'years'}${isFuture ? '' : ' ago'}`;",
" if (days > 0) return `${isFuture ? 'in ' : ''}${days} ${days === 1 ? 'day' : 'days'}${isFuture ? '' : ' ago'}`;",
" if (hours > 0) return `${isFuture ? 'in ' : ''}${hours} ${hours === 1 ? 'hour' : 'hours'}${isFuture ? '' : ' ago'}`;",
" if (minutes > 0) return `${isFuture ? 'in ' : ''}${minutes} ${minutes === 1 ? 'minute' : 'minutes'}${isFuture ? '' : ' ago'}`;",
"",
" return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`;",
"}",
"",
"// usage",
"const pastDate = new Date('2021-12-29 13:00:00');",
"const futureDate = new Date('2026-12-29 13:00:00');",
"console.log(timeAgoOrAhead(pastDate)); // x years ago",
"console.log(timeAgoOrAhead(new Date())); // just now",
"console.log(timeAgoOrAhead(futureDate)); // in x years"
],
"tags": ["javascript", "date", "time", "relative", "future", "past", "utility"],
"author": "Yugveer06"
}
]
},
Expand Down

0 comments on commit 74ead62

Please sign in to comment.