Open for full-time roles. Contact Me

Get Relative Time

A helpful utility to display relative time in short format like 3h, 2mo, 1y, 30s.

ts
1import { formatDistanceToNow } from "date-fns";
2
3export function getRelativeTime(date: Date) {
4  const distance = formatDistanceToNow(new Date(date), {
5    includeSeconds: true,
6  });
7
8  return distance
9    .replace("about ", "")
10    .replace("less than ", "")
11    .replace(" minutes", "m")
12    .replace("half a minute", "30s")
13    .replace("a minute", "1m")
14    .replace(" minute", "m")
15    .replace(" hours", "h")
16    .replace(" hour", "h")
17    .replace(" days", "d")
18    .replace(" day", "d")
19    .replace(" weeks", "w")
20    .replace(" week", "w")
21    .replace(" months", "mo")
22    .replace(" month", "mo")
23    .replace(" years", "y")
24    .replace(" year", "y")
25    .replace(" seconds", "s")
26    .replace(" second", "s");
27}

Loved this post?

Comments

Interested in
working
with me?

Let's Connect

Stay in touch 👇

© 2021 - 2025 itsrakesh. v2.