DateTime
The DateTime module provides a structured type for working with dates and times. Unlike the Time module which uses raw Unix timestamps, DateTime provides a rich type with functions for parsing, formatting, and extracting individual date/time components.
Use DateTime when you need to work with structured date/time values,
parse date strings, or extract components like year, month, and day.
Use Time for simple timestamp arithmetic and comparisons.
Current Time
dt = DateTime.now
println (DateTime.format dt "%Y-%m-%d %H:%M:%S")
# => "2024-12-19 14:30:00"
Timestamp Conversion
ts = 1702998600000 # Dec 19, 2024 14:30:00 UTC
dt = DateTime.from-timestamp ts
println (DateTime.year dt)
# => 2024
dt = DateTime.now
ts = DateTime.to-timestamp dt
println ts
# => 1702998600000
Parsing and Formatting
Ok DateTime on success or Err ParseError on failure.
result = DateTime.parse "2024-12-19" "%Y-%m-%d"
match result
| Ok dt -> println (DateTime.year dt)
| Err e -> println "Parse error"
# => 2024
# Parse with time
result2 = DateTime.parse "2024-12-19 14:30:00" "%Y-%m-%d %H:%M:%S"
dt = DateTime.now
# ISO date format
println (DateTime.format dt "%Y-%m-%d")
# => "2024-12-19"
# Full date and time
println (DateTime.format dt "%Y-%m-%d %H:%M:%S")
# => "2024-12-19 14:30:00"
# Human-readable format
println (DateTime.format dt "%B %d, %Y")
# => "December 19, 2024"
Common format specifiers:
%Y- Four-digit year (2024)%m- Month as zero-padded number (01-12)%d- Day as zero-padded number (01-31)%H- Hour in 24-hour format (00-23)%M- Minute (00-59)%S- Second (00-59)%B- Full month name (December)%b- Abbreviated month name (Dec)%A- Full weekday name (Thursday)%a- Abbreviated weekday name (Thu)
Component Extraction
These functions extract individual components from a DateTime value. All functions return integers.
dt = DateTime.now
println (DateTime.year dt)
# => 2024
dt = DateTime.now
println (DateTime.month dt)
# => 12
dt = DateTime.now
println (DateTime.day dt)
# => 19
dt = DateTime.now
println (DateTime.hour dt)
# => 14
dt = DateTime.now
println (DateTime.minute dt)
# => 30
dt = DateTime.now
println (DateTime.second dt)
# => 0
dt = DateTime.now
println (DateTime.millisecond dt)
# => 500
Here is an example using multiple DateTime functions together:
# Parse a date string
result = DateTime.parse "2024-12-19 14:30:45" "%Y-%m-%d %H:%M:%S"
match result
| Ok dt ->
println "Year: ${DateTime.year dt}"
println "Month: ${DateTime.month dt}"
println "Day: ${DateTime.day dt}"
println "Time: ${DateTime.hour dt}:${DateTime.minute dt}:${DateTime.second dt}"
# Convert to timestamp and back
ts = DateTime.to-timestamp dt
dt2 = DateTime.from-timestamp ts
println (DateTime.format dt2 "%B %d, %Y at %H:%M")
# => "December 19, 2024 at 14:30"
| Err e ->
println "Failed to parse date"