Time in Julia

Julia offers extensive support for times and durations; here are some examples.

using Dates

# We'll start by getting the current time.
now = now()
println(now)

# You can build a DateTime struct by providing the
# year, month, day, etc. Times are always associated
# with a TimeZone, i.e. time zone.
then = DateTime(2009, 11, 17, 20, 34, 58, 651)
println(then)

# You can extract the various components of the time
# value as expected.
println(year(then))
println(month(then))
println(day(then))
println(hour(then))
println(minute(then))
println(second(then))
println(millisecond(then))
println(timezone(now))

# The Monday-Sunday dayname is also available.
println(dayname(then))

# These methods compare two times, testing if the
# first occurs before, after, or at the same time
# as the second, respectively.
println(then < now)
println(then > now)
println(then == now)

# The `-` operator returns a Duration representing
# the interval between two times.
diff = now - then
println(diff)

# We can compute the length of the duration in
# various units.
println(Dates.value(Dates.Hour(diff)))
println(Dates.value(Dates.Minute(diff)))
println(Dates.value(Dates.Second(diff)))
println(Dates.value(Dates.Millisecond(diff)))

# You can use `+` to advance a time by a given
# duration, or with a `-` to move backwards by a
# duration.
println(then + diff)
println(then - diff)

To run the program, save it as time_example.jl and use julia time_example.jl.

$ julia time_example.jl
2023-05-24T12:34:56.789
2009-11-17T20:34:58.651
2009
11
17
20
34
58
651
UTC
Tuesday
true
false
false
118271d 16h 0m 1s 138ms
2838528
170311681
10218700861
10218700861138
2023-05-24T12:34:56.789
1996-05-13T04:34:59.513

Next, we’ll look at the related idea of time relative to the Unix epoch.