Skip to content

Commit

Permalink
Enhance relative time
Browse files Browse the repository at this point in the history
  • Loading branch information
khammami committed Jan 31, 2024
1 parent 9f416b7 commit 383655b
Showing 1 changed file with 24 additions and 29 deletions.
53 changes: 24 additions & 29 deletions src/utils/datetime.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,28 @@
const relativeTimeFormat = new Intl.RelativeTimeFormat('en', {
style: 'short',
numeric: 'auto',
})
});

export function getRelativeDateString(date: Date) {
const now = new Date()
const diff = (date.getTime() - now.getTime()) / 1000
let relativeDate
if (Math.abs(diff) < 60) {
relativeDate = relativeTimeFormat.format(Math.floor(diff), 'second')
} else if (Math.abs(diff) < 60 * 60) {
relativeDate = relativeTimeFormat.format(Math.floor(diff / 60), 'minute')
} else if (Math.abs(diff) < 24 * 60 * 60) {
relativeDate = relativeTimeFormat.format(Math.floor(diff / 60 / 60), 'hour')
} else if (Math.abs(diff) < 30 * 24 * 60 * 60) {
relativeDate = relativeTimeFormat.format(
Math.floor(diff / 60 / 60 / 24),
'day',
)
} else if (Math.abs(diff) < 365 * 24 * 60 * 60) {
relativeDate = relativeTimeFormat.format(
date.getMonth() - now.getMonth(),
'month',
)
} else {
relativeDate = relativeTimeFormat.format(
date.getFullYear() - now.getFullYear(),
'month',
)
}
return relativeDate
}
// Array reprsenting one minute, hour, day, week, month, etc in seconds
const cutoffs = [60, 3600, 86400, 86400 * 7, 86400 * 30, 86400 * 365, Infinity];

// Array equivalent to the above but in the string representation of the units
const units: Intl.RelativeTimeFormatUnit[] = ["second", "minute", "hour", "day", "week", "month", "year"];

export function getRelativeDateString(date: Date): string {
// Allow dates or times to be passed
const timeMs = typeof date === "number" ? date : date.getTime();

// Get the amount of seconds between the given date and now
const deltaSeconds = Math.round((timeMs - Date.now()) / 1000);

// Grab the ideal cutoff unit
const unitIndex = cutoffs.findIndex(cutoff => cutoff > Math.abs(deltaSeconds));

// Get the divisor to divide from the seconds. E.g. if our unit is "day" our divisor
// is one day in seconds, so we can divide our seconds by this to get the # of days
const divisor = unitIndex ? cutoffs[unitIndex - 1] : 1;

// Intl.RelativeTimeFormat do its magic
return relativeTimeFormat.format(Math.floor(deltaSeconds / divisor), units[unitIndex]);
}

0 comments on commit 383655b

Please sign in to comment.