Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions packages/utils/src/formatting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ describe('formatAbsoluteDate', () => {
expect(result).toMatch(/May/)
expect(result).toMatch(/2023/)
})

it('returns the original input for an unparseable date', () => {
expect(formatAbsoluteDate('not-a-date')).toBe('not-a-date')
})
})

describe('formatTime', () => {
Expand Down Expand Up @@ -99,9 +103,10 @@ describe('formatCompactTimestamp', () => {
expect(result).toMatch(/^\d{2}-\d{2} \d{2}:\d{2}$/)
})

it('returns a formatted string even for invalid dates (no throw)', () => {
it('returns the original input for invalid dates instead of a NaN string', () => {
const result = formatCompactTimestamp('not-a-date')
expect(typeof result).toBe('string')
expect(result).toBe('not-a-date')
expect(result).not.toContain('NaN')
})
})

Expand Down
10 changes: 10 additions & 0 deletions packages/utils/src/formatting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,11 @@ export function formatDate(date: Date): string {
*/
export function formatAbsoluteDate(dateString: string): string {
const date = new Date(dateString)
// An unparseable string yields an Invalid Date whose formatters return
// "Invalid Date"; fall back to the original input instead.
if (Number.isNaN(date.getTime())) {
return dateString
Comment on lines +108 to +110

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Document the fallback contract

Both exported functions now return the original input for invalid dates, but their TSDoc still promises a formatted date string. Documenting this fallback prevents consumers from incorrectly assuming that every result conforms to the advertised fixed date format.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

}
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
Expand Down Expand Up @@ -150,6 +155,11 @@ export function formatTimeWithSeconds(date: Date, includeTimezone = true): strin
export function formatCompactTimestamp(iso: string): string {
try {
const d = new Date(iso)
// Invalid dates do not throw; their getters return NaN, so the catch
// below never fires. Guard explicitly and fall back to the input string.
if (Number.isNaN(d.getTime())) {
return iso
}
const mm = String(d.getMonth() + 1).padStart(2, '0')
const dd = String(d.getDate()).padStart(2, '0')
const hh = String(d.getHours()).padStart(2, '0')
Expand Down