Skip to content

Instantly share code, notes, and snippets.

@Klerith
Created November 9, 2022 19:56
Show Gist options
  • Save Klerith/384f1404aba285f686fd082166a7af3c to your computer and use it in GitHub Desktop.
Save Klerith/384f1404aba285f686fd082166a7af3c to your computer and use it in GitHub Desktop.
Time Since
export const timeSince = ( date: string ) => {
const baseDate = new Date(date)
const seconds = Math.floor(( new Date().getTime() - baseDate.getTime() ) / 1000);
let interval = seconds / 31536000;
if (interval > 1) {
return Math.floor(interval) === 1
? Math.floor(interval) + ' year'
: Math.floor(interval) + ' years';
}
interval = seconds / 2592000;
if (interval > 1) {
return Math.floor(interval) === 1
? Math.floor(interval) + ' month'
: Math.floor(interval) + ' months';
}
interval = seconds / 86400;
if (interval > 1) {
return Math.floor(interval) === 1
? Math.floor(interval) + ' day'
: Math.floor(interval) + ' days';
}
interval = seconds / 3600;
if (interval > 1) {
return Math.floor(interval) === 1
? Math.floor(interval) + ' hour'
: Math.floor(interval) + ' hours';
}
interval = seconds / 60;
if (interval > 1) {
return Math.floor(interval) === 1
? Math.floor(interval) + ' minute'
: Math.floor(interval) + ' minutes';
}
return Math.floor(interval) === 1
? Math.floor(interval) + ' second'
: Math.floor(interval) + ' seconds';
}
@sjosuerojas
Copy link

Buenas profe, que te parece este codiguillo que hace lo mismo, pero un poco más compacto y legible.

export const timeSince = (dateString) => {
  const baseDate = new Date(dateString);
  const now = new Date();
  const seconds = Math.floor((now - baseDate) / 1000);

  const intervals = [
    { label: 'year', seconds: 31536000 },
    { label: 'month', seconds: 2592000 },
    { label: 'day', seconds: 86400 },
    { label: 'hour', seconds: 3600 },
    { label: 'minute', seconds: 60 },
    { label: 'second', seconds: 1 },
  ];

  for (const { label, seconds: intervalSeconds } of intervals) {
    const interval = seconds / intervalSeconds;
    if (interval >= 1) {
      const roundedInterval = Math.floor(interval);
      return `${roundedInterval} ${label}${roundedInterval === 1 ? '' : 's'}`;
    }
  }

  return 'just now';
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment