MCPcopy
hub / github.com/codeaashu/claude-code / formatRelativeTime

Function formatRelativeTime

src/utils/format.ts:144–184  ·  view source on GitHub ↗
(
  date: Date,
  options: RelativeTimeOptions & { now?: Date } = {},
)

Source from the content-addressed store, hash-verified

142}
143
144export 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
186export function formatRelativeTimeAgo(
187 date: Date,

Callers 2

ResumeTaskFunction · 0.85
formatRelativeTimeAgoFunction · 0.85

Calls 1

getRelativeTimeFormatFunction · 0.85

Tested by

no test coverage detected