Created
November 10, 2023 20:22
-
-
Save 32teeth/dc526f139d9152c8b1ab005b4d3dba9d to your computer and use it in GitHub Desktop.
Cheap and dirty date formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const date = new Date(); | |
date.setDate(date.getDate() - 2); // Set date to 2 days ago | |
const now = new Date(); | |
const diffInMilliseconds = now - date; | |
const seconds = Math.floor(diffInMilliseconds / 1000); | |
const formatter = new Intl.RelativeTimeFormat('en', { numeric: 'auto' }); | |
const formattedDate = formatter.format( | |
seconds < 60 | |
? -seconds | |
: seconds < 3600 | |
? -Math.floor(seconds / 60) | |
: seconds < 86400 | |
? -Math.floor(seconds / 3600) | |
: now.getDate() === date.getDate() && now.getMonth() === date.getMonth() && now.getFullYear() === date.getFullYear() | |
? -Math.floor(seconds / 86400) | |
: now.getMonth() === date.getMonth() && now.getFullYear() === date.getFullYear() | |
? -Math.floor(now.getDate() - date.getDate()) | |
: -Math.floor(now.getMonth() - date.getMonth()), | |
seconds < 60 | |
? 'second' | |
: seconds < 3600 | |
? 'minute' | |
: seconds < 86400 | |
? 'hour' | |
: now.getDate() === date.getDate() && now.getMonth() === date.getMonth() && now.getFullYear() === date.getFullYear() | |
? 'day' | |
: now.getMonth() === date.getMonth() && now.getFullYear() === date.getFullYear() | |
? 'day' | |
: 'month' | |
); | |
console.log(formattedDate); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment