Created
December 1, 2023 17:19
-
-
Save ededejr/80afae1aa0f96e298da6e2fd90e28c5c to your computer and use it in GitHub Desktop.
a react hook for formatting timestamps relative to now
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
function useRelativeTimestamp(ts: number) { | |
const now = Date.now(); | |
let displayTime = ""; | |
const diff = now - ts; | |
const timestamp = new Date(ts); | |
if (diff <= 1000 * 60 * 60) { | |
const formatter = new Intl.RelativeTimeFormat("en", { numeric: "auto" }); | |
const diffInSecs = Math.round(diff / 1000); | |
if (diffInSecs < 60) { | |
displayTime = formatter.format(-diffInSecs, "seconds"); | |
} else { | |
const diffInMinutes = Math.round(diffInSecs / 60); | |
displayTime = formatter.format(-diffInMinutes, "minutes"); | |
} | |
} else if (diff <= 1000 * 60 * 60 * 24) { | |
displayTime = timestamp.toLocaleTimeString([], { | |
hour: "numeric", | |
minute: "numeric", | |
}); | |
} else if (diff <= 1000 * 60 * 60 * 24 * 1) { | |
displayTime = timestamp.toLocaleTimeString([], { | |
hour: "numeric", | |
minute: "numeric", | |
weekday: "short", | |
}); | |
} else if (diff <= 1000 * 60 * 60 * 24 * 2) { | |
displayTime = `Yesterday, ${timestamp.toLocaleTimeString([], { | |
hour: "numeric", | |
minute: "numeric", | |
})}`; | |
} else { | |
displayTime = timestamp.toLocaleDateString([], { | |
hour: "numeric", | |
minute: "numeric", | |
month: "short", | |
day: "numeric", | |
}); | |
} | |
return displayTime; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment