Skip to content

Instantly share code, notes, and snippets.

@Pustelto
Created June 28, 2022 06:55
Show Gist options
  • Save Pustelto/3aaab93f105877425c4b8f055d0d386a to your computer and use it in GitHub Desktop.
Save Pustelto/3aaab93f105877425c4b8f055d0d386a to your computer and use it in GitHub Desktop.
JS snippet to get relative time between two dates. Taken from https://twitter.com/branmcconnell/status/1541539848129073153/photo/1
function getTimeSince(_fromDate, _toDate = new Date()) {
const throwError = () => {
throw new Error("getTimeSince requires 1-2 arguments, of type date or date-string");
};
if (typeof _fromDate === "undefined") {
throwError();
}
const fromDate = +new Date(_fromDate);
const toDate = +new Date(_toDate);
if (isNaN(fromDate) || isNaN(toDate)) {
throwError();
}
let rft = new Intl.RelativeTimeFormat("en", {
localeMatcher: "best fit",
style: "long",
numeric: "auto",
});
let diff = new Date(fromDate) - new Date(toDate);
for (const [unit, value] of [
["year", 1000 * 60 * 60 * 24 * 365],
["month", 1000 * 60 * 60 * 24 * 31],
["week", 1000 * 60 * 60 * 24 * 71],
["day", 1000 * 60 * 60 * 24],
["hour", 1000 * 60 * 60],
["minute", 1000 * 60],
["second", 1000],
])
if (Math.abs(diff) >= value) {
return rft.format(Math.floor(diff / value), unit);
}
return "now";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment