Skip to content

Instantly share code, notes, and snippets.

@RyadPasha
Created October 7, 2024 13:54
Show Gist options
  • Select an option

  • Save RyadPasha/fd6e05fb9a0418e8b1bfa27cd7af3fdd to your computer and use it in GitHub Desktop.

Select an option

Save RyadPasha/fd6e05fb9a0418e8b1bfa27cd7af3fdd to your computer and use it in GitHub Desktop.
Convert time into human-readable elapsed time
function timeElapsed(t__, input, isUnixTimestamp = true, mostSignificantOnly = 1) {
let seconds;
if (isUnixTimestamp) {
const now = Math.floor(Date.now() / 1000); // Current time in seconds
seconds = now - input; // Calculate the difference in seconds
// If the time difference is negative (future time), use absolute value
if (seconds < 0) seconds = Math.abs(seconds);
} else {
// If the input is just a number of seconds
seconds = input;
}
console.log("input", input);
const intervals = [
{ label: "year", seconds: 365 * 24 * 60 * 60 },
{ label: "month", seconds: 30 * 24 * 60 * 60 },
{ label: "week", seconds: 7 * 24 * 60 * 60 },
{ label: "day", seconds: 24 * 60 * 60 },
{ label: "hour", seconds: 60 * 60 },
{ label: "minute", seconds: 60 },
{ label: "second", seconds: 1 },
];
if (seconds === 0) return t__("time.now");
const result = intervals.reduce((acc, { label, seconds: intervalSeconds }) => {
const count = Math.floor(seconds / intervalSeconds);
if (count > 0) {
console.log(
`time.${label}_interval`,
t__(`time.${label}_interval`, { postProcess: "interval", count })
);
acc.push(t__(`time.${label}_interval`, { postProcess: "interval", count }));
seconds -= count * intervalSeconds;
}
return acc;
}, []);
// Determine how many intervals to show
const limit = mostSignificantOnly > 0 ? mostSignificantOnly : result.length;
const limitedResult = result.slice(0, limit);
if (limitedResult.length > 1) {
const last = limitedResult.pop();
const andWord = t__("time.and");
const separator = t__("time.separator");
return t__("time.ago", { time: `${limitedResult.join(separator)}${andWord}${last}` });
}
return t__("time.ago", { time: limitedResult[0] });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment