web/src/utils/dates-n-stuff.ts

33 lines · 849 bytes

 1export const formatDate = (date: string): string => {
 2  return new Date(date).toLocaleDateString('en-GB', {
 3    day: '2-digit',
 4    month: 'short',
 5    year: '2-digit',
 6  });
 7};
 8
 9export const timestampToDate = (timestamp: number): string => {
10  return new Date(timestamp).toLocaleDateString('en-GB', {
11    day: '2-digit',
12    month: 'short',
13    year: '2-digit',
14  });
15};
16
17export const timeAgo = (dateStr: string): string => {
18  const seconds = Math.floor(
19    (new Date().getTime() - new Date(dateStr).getTime()) / 1000,
20  );
21  const intervals = {
22    year: 31536000,
23    month: 2592000,
24    day: 86400,
25    hour: 3600,
26    minute: 60,
27  };
28  for (const [key, value] of Object.entries(intervals)) {
29    const count = Math.floor(seconds / value);
30    if (count > 0) return `${count} ${key}${count !== 1 ? 's' : ''} ago`;
31  }
32  return 'just now';
33};