Last active
February 27, 2023 04:03
-
-
Save lewdev/f51284b4960db029c3b90a2bb76f1c41 to your computer and use it in GitHub Desktop.
π
Date Distance JavaScript function (i.e. "3mo ago", "5d until")
This file contains hidden or 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
| <pre id=o></pre> | |
| <script> | |
| const TIME = [1e3, "s", 6e4, "min", 36e5, "hr", 864e5, "d", 2592e6, "wk", 2592e6, "mo", 31536e6, "yr"]; | |
| const dateDistance = dateStr => { | |
| const now = new Date().getTime(); | |
| let diff = now - new Date(dateStr).getTime(); | |
| let agoOrUntil = " ago"; | |
| if (diff < 0) { agoOrUntil = " until"; diff = Math.abs(diff); } | |
| for (let i = 12; i >= 0; i-=2) { | |
| const t = TIME[i]; | |
| if (diff >= t) return ~~(diff / t) + TIME[i + 1] + agoOrUntil; | |
| } | |
| return diff + "ms" + agoOrUntil; | |
| }; | |
| o.innerHTML = dateDistance("2023-02-27T04:01:00.497Z"); | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment