Time Formatting Parsing in Julia

Julia supports time formatting and parsing via pattern-based layouts.

using Dates
using Printf

# Here's a basic example of formatting a time
# according to ISO 8601 / RFC 3339
t = now()
println(Dates.format(t, "yyyy-mm-ddTHH:MM:SSzzz"))

# Time parsing uses the same format strings as formatting
t1 = DateTime("2012-11-01T22:08:41+00:00", "yyyy-mm-ddTHH:MM:SSzzz")
println(t1)

# Format and parse use example-based layouts. You can
# supply custom layouts. Layouts must use the reference time
# to show the pattern with which to format/parse a given time/string.

println(Dates.format(t, "I:MMAP"))
println(Dates.format(t, "E, d u yyyy HH:MM:SS"))
println(Dates.format(t, "yyyy-mm-ddTHH:MM:SS.ssszzz"))

form = "H MM PP"
t2 = DateTime("8 41 PM", form)
println(t2)

# For purely numeric representations you can also
# use standard string formatting with the extracted
# components of the time value.
@printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
    year(t), month(t), day(t),
    hour(t), minute(t), second(t))

# parse will throw an error on malformed input
# explaining the parsing problem.
try
    DateTime("8:41PM", "E, d u yyyy HH:MM:SS")
catch e
    println(e)
end

When you run this program, you’ll see output similar to:

2023-05-15T10:30:45+01:00
2012-11-01T22:08:41
10:30AM
Mon, 15 May 2023 10:30:45
2023-05-15T10:30:45.123+01:00
0000-01-01T20:41:00
2023-05-15T10:30:45-00:00
ArgumentError("Couldn't parse date 8:41PM using format E, d u yyyy HH:MM:SS")

In Julia, we use the Dates module for handling time-related operations. The DateTime type represents a point in time, and we can format and parse it using format strings.

Julia’s date formatting is somewhat different from other languages. Instead of using predefined constants like RFC3339, we specify the format string directly. The format specifiers are similar to those in other languages, but there are some differences. For example, yyyy for year, mm for month, dd for day, HH for hour, MM for minute, SS for second, and zzz for time zone.

For parsing, we use the same format string as for formatting. If the parsing fails, Julia will throw an ArgumentError with a description of the problem.

Julia also provides functions to extract individual components of a date/time, such as year(), month(), day(), etc., which can be used for custom formatting.

Remember that Julia is 1-indexed, so months and days start from 1, not 0.