(
date: Date,
options: RelativeTimeOptions & { now?: Date } = {},
)
| 142 | } |
| 143 | |
| 144 | export function formatRelativeTime( |
| 145 | date: Date, |
| 146 | options: RelativeTimeOptions & { now?: Date } = {}, |
| 147 | ): string { |
| 148 | const { style = 'narrow', numeric = 'always', now = new Date() } = options |
| 149 | const diffInMs = date.getTime() - now.getTime() |
| 150 | // Use Math.trunc to truncate towards zero for both positive and negative values |
| 151 | const diffInSeconds = Math.trunc(diffInMs / 1000) |
| 152 | |
| 153 | // Define time intervals with custom short units |
| 154 | const intervals = [ |
| 155 | { unit: 'year', seconds: 31536000, shortUnit: 'y' }, |
| 156 | { unit: 'month', seconds: 2592000, shortUnit: 'mo' }, |
| 157 | { unit: 'week', seconds: 604800, shortUnit: 'w' }, |
| 158 | { unit: 'day', seconds: 86400, shortUnit: 'd' }, |
| 159 | { unit: 'hour', seconds: 3600, shortUnit: 'h' }, |
| 160 | { unit: 'minute', seconds: 60, shortUnit: 'm' }, |
| 161 | { unit: 'second', seconds: 1, shortUnit: 's' }, |
| 162 | ] as const |
| 163 | |
| 164 | // Find the appropriate unit |
| 165 | for (const { unit, seconds: intervalSeconds, shortUnit } of intervals) { |
| 166 | if (Math.abs(diffInSeconds) >= intervalSeconds) { |
| 167 | const value = Math.trunc(diffInSeconds / intervalSeconds) |
| 168 | // For short style, use custom format |
| 169 | if (style === 'narrow') { |
| 170 | return diffInSeconds < 0 |
| 171 | ? `${Math.abs(value)}${shortUnit} ago` |
| 172 | : `in ${value}${shortUnit}` |
| 173 | } |
| 174 | // For days and longer, use long style regardless of the style parameter |
| 175 | return getRelativeTimeFormat('long', numeric).format(value, unit) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // For values less than 1 second |
| 180 | if (style === 'narrow') { |
| 181 | return diffInSeconds <= 0 ? '0s ago' : 'in 0s' |
| 182 | } |
| 183 | return getRelativeTimeFormat(style, numeric).format(0, 'second') |
| 184 | } |
| 185 | |
| 186 | export function formatRelativeTimeAgo( |
| 187 | date: Date, |
no test coverage detected