Skip to main content

Dates

Date parsing and formatting utilities. Re-exports format, isValid, and parseISO from date-fns and adds safe parsing/formatting helpers.

Constants

import { dateFormat, dateTimeFormat } from '@repo/utils'

dateFormat // 'yyyy-MM-dd'
dateTimeFormat // "yyyy-MM-dd'T'HH:mm"

Re-exports from date-fns

format

Formats a Date into a string using the given format pattern.

import { format } from '@repo/utils'

format(new Date(2024, 5, 15), 'yyyy-MM-dd')
// '2024-06-15'

parseISO

Parses an ISO 8601 date string into a Date.

import { parseISO } from '@repo/utils'

parseISO('2024-06-15T10:30:00Z')
// Date object: 2024-06-15T10:30:00.000Z

isValid

Returns true if the given date is valid.

import { isValid } from '@repo/utils'

isValid(new Date('2024-06-15')) // true
isValid(new Date('not-a-date')) // false

parseValid

Parses a date string using a format pattern. Returns the Date if valid, undefined otherwise.

import { parseValid } from '@repo/utils'

function parseValid(value: string | undefined, dateFormat: string): Date | undefined

Example

import { parseValid, dateFormat } from '@repo/utils'

parseValid('2024-06-15', dateFormat)
// Date object: 2024-06-15

parseValid('not-a-date', dateFormat)
// undefined

parseValid(undefined, dateFormat)
// undefined

formatValid

Formats a Date into a string if the date is valid. Returns undefined for invalid or missing dates. Defaults to 'yyyy-MM-dd HH:mm' format.

import { formatValid } from '@repo/utils'

function formatValid(
value: Date | undefined,
dateFormat?: string // default: 'yyyy-MM-dd HH:mm'
): string | undefined

Example

import { formatValid, dateFormat } from '@repo/utils'

formatValid(new Date(2024, 5, 15, 10, 30), dateFormat)
// '2024-06-15'

formatValid(new Date(2024, 5, 15, 10, 30))
// '2024-06-15 10:30' (uses default format)

formatValid(undefined)
// undefined

formatValid(new Date('invalid'))
// undefined