Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blog timestamp shows wrong time ago. #688

Open
nisabmohd opened this issue Jan 3, 2024 · 1 comment
Open

Blog timestamp shows wrong time ago. #688

nisabmohd opened this issue Jan 3, 2024 · 1 comment

Comments

@nisabmohd
Copy link

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
Copy link

heykapil commented Jan 20, 2024

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})`;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants