OpenForm

datetime

Last updated on

Validate datetime strings

Validate datetime strings in ISO 8601 format. The Datetime primitive ensures timestamps are properly formatted with date, time, and timezone information.

Examples

Creating datetimes

// Direct validation
const dt = open.datetime('2024-01-15T10:30:00Z')

// Parse unknown input
const dt = open.datetime.parse(jsonData)

// Get current datetime
const now = open.datetime.now()

// Convert from Date object
const dt = open.datetime.fromDate(new Date())

// Check validity without throwing
if (open.datetime.isValid('2024-01-15T10:30:00Z')) {
  console.log('Valid datetime')
}

Parsing external data

// Parse unknown input (throws on error)
const dt = open.datetime.parse(userInput)

// Safe parsing (returns result object)
const result = open.datetime.safeParse(userInput)
if (result.success) {
  console.log(`Datetime: ${result.data}`)
} else {
  console.error(result.error.message)
}

Using with forms

const form = open.form({
  name: 'appointment',
  fields: {
    scheduledAt: { type: 'datetime', label: 'Appointment Time' }
  }
})

const filled = form.fill({
  fields: {
    scheduledAt: open.datetime('2024-06-15T14:30:00Z')
  }
})

API

Direct Call

open.datetime(input: string): string

Pass a datetime string for validation. Returns the validated string or throws on error.

const dt = open.datetime('2024-01-15T10:30:00Z')

Static Methods

parse: (input: unknown) => string
Parse unknown input (throws on error)
safeParse: (input: unknown) => Result<string>
Parse unknown input (returns result object)
isValid: (input: string) => boolean
Check if a string is a valid datetime
fromDate: (date: Date) => string
Convert a JavaScript Date to ISO datetime string
now: () => string
Get current datetime as ISO string

Format

The Datetime primitive expects and returns strings in ISO 8601 datetime format:

YYYY-MM-DDTHH:mm:ssZ
YYYY-MM-DDTHH:mm:ss.sssZ
YYYY-MM-DDTHH:mm:ss±HH:mm
ComponentDescriptionExample
YYYY-MM-DDDate portion2024-01-15
TSeparatorT
HH:mm:ssTime (24-hour)10:30:00
.sssMilliseconds (optional).123
ZUTC timezoneZ
±HH:mmTimezone offset+05:30

Validation

The Datetime primitive validates:

  • String must be a valid ISO 8601 datetime format
  • Date portion must be valid (see date)
  • Time portion must be valid (see time)
  • Timezone must be specified (Z or offset)
// Valid
open.datetime('2024-01-15T10:30:00Z')
open.datetime('2024-01-15T10:30:00.123Z')
open.datetime('2024-01-15T10:30:00+05:30')
open.datetime('2024-01-15T10:30:00-08:00')

// Invalid - throws Error
open.datetime('2024-01-15')
// Error: Invalid Datetime: missing time component

open.datetime('2024-01-15T10:30:00')
// Error: Invalid Datetime: missing timezone

open.datetime('2024-01-15 10:30:00Z')
// Error: Invalid Datetime: must use T separator

open.datetime('not-a-datetime')
// Error: Invalid Datetime: invalid format

Related

On this page