Skip to content

Instantly share code, notes, and snippets.

@zaosoula
Forked from danott/relative_time.php
Last active May 4, 2022 10:10
Show Gist options
  • Save zaosoula/8667c2750f67b1ca6833345e286dfc3c to your computer and use it in GitHub Desktop.
Save zaosoula/8667c2750f67b1ca6833345e286dfc3c to your computer and use it in GitHub Desktop.
Twitter style relative time.
const computeRelativeTime = (time) => {
if(typeof time === 'string') {
return computeRelativeTime(new Date(time));
}
const plural = (val) => val !== 1 ? 's' : '';
const format = (val, unit) => `${val} ${unit}${plural(val)} ago`;
let diff = (Date.now() - time.getTime()) / 1000;
if (diff<60) {
return format(diff, 'second');
}
diff = Math.round(diff/60);
if (diff<60) {
return format(diff, 'minute');
}
diff = Math.round(diff/60);
if (diff<24){
return format(diff, 'hour');
}
diff = Math.round(diff/24);
if (diff<7){
return format(diff, 'day');
}
diff = Math.round(diff/7);
if (diff<4){
return format(diff, 'week');
}
return `on ${time.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}`;
}
const computeRelativeTime = (time: string | Date): string => {
if(typeof time === 'string') {
return computeRelativeTime(new Date(time));
}
const plural = (val: number) => val !== 1 ? 's' : '';
const format = (val: number, unit: string) => `${val} ${unit}${plural(val)} ago`;
let diff = (Date.now() - time.getTime()) / 1000;
if (diff<60) {
return format(diff, 'second');
}
diff = Math.round(diff/60);
if (diff<60) {
return format(diff, 'minute');
}
diff = Math.round(diff/60);
if (diff<24){
return format(diff, 'hour');
}
diff = Math.round(diff/24);
if (diff<7){
return format(diff, 'day');
}
diff = Math.round(diff/7);
if (diff<4){
return format(diff, 'week');
}
return `on ${time.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment