leerob / site

My site built with Next.js, Tailwind, and Vercel.
https://leerob.com
7.2k stars 1.39k forks source link

Blog timestamp shows wrong time ago. #688

Closed nisabmohd closed 2 months ago

nisabmohd commented 10 months ago

On blog page the timestamp is shown wrong time ago. You can find below screenshot that the blog is created on August 7 2023 but shows a year ago.

Screenshot_2024-01-03-14-01-23-69_40deb401b9ffe8e1df2f1cc5ba480b12.jpg

heykapil commented 10 months ago

Try this.

function formatDate(date: string) {
  noStore();
  let currentDate = new Date();
  if (!date.includes('T')) {
    date = `${date}T00:00:00`;
  }
  let targetDate = new Date(date);
- let yearsAgo = currentDate.getFullYear() - targetDate.getFullYear();
- let monthsAgo = currentDate.getMonth() - targetDate.getMonth();
- let daysAgo = currentDate.getDate() - targetDate.getDate();
+ let yearsAgo = 0, monthsAgo = 0, daysAgo = 0;
+ let daysDiff = Math.round((currentDate.getTime() - targetDate.getTime()) / (1000 * 3600 * 24));
+  while (daysDiff) {
+  if (daysDiff >= 365) {
+      yearsAgo++;
+     daysDiff -= 365;
+    } else if (daysDiff >= 30) {
+      monthsAgo++;
+     daysDiff -= 30;
+    } else {
+     daysAgo++;
+      daysDiff--;
+   }
+  }
  let formattedDate = '';
  if (yearsAgo > 0) {
    formattedDate = `${yearsAgo}y ago`;
  } else if (monthsAgo > 0) {
    formattedDate = `${monthsAgo}mo ago`;
  } else if (daysAgo > 0) {
    formattedDate = `${daysAgo}d ago`;
  } else {
    formattedDate = 'Today';
  }
  let fullDate = targetDate.toLocaleString('en-us', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
  });
  return `${fullDate} (${formattedDate})`;
}
leerob commented 2 months ago

Moved to a different design: https://github.com/leerob/leerob.io/pull/727

Nithur-M commented 1 month ago

Hey @leerob, how would you extend your new minimal design for the dedicated blog posts list page and add additional data like cover image, published date, etc? TIA.