Skip to content
AgileLogics
5 min read

Dates and Times

Prerequisites: Modules

The Dates standard library handles calendar dates, times, and durations:

using Dates

d = Date(2024, 2, 28)
println(d, " ", d + Day(1), " ", d + Day(2))
println(year(d), " ", month(d), " ", day(d), " ", dayname(d))
println(isleapyear(d), " ", daysinmonth(d))
println(Date(2024, 12, 25) - Date(2024, 1, 1))
println(d + Month(1), " ", lastdayofmonth(Date(2023, 2, 1)))

dt = DateTime(2024, 5, 17, 14, 30)
println(dt, " ", dt + Hour(12))
println(Dates.format(dt, "dd u yyyy HH:MM"))
2024-02-28 2024-02-29 2024-03-01
2024 2 28 Wednesday
true 29
359 days
2024-03-28 2023-02-28
2024-05-17T14:30:00 2024-05-18T02:30:00
17 May 2024 14:30
  • Date is a calendar day; DateTime adds a time with millisecond precision. Neither stores a time zone (use TimeZones.jl for that).
  • Periods like Day, Month, Hour, Minute can be added and subtracted. Subtracting two dates gives a number of days.

Parsing and formatting

using Dates

d = Date("17/05/2024", dateformat"dd/mm/yyyy")
println(d)
println(Dates.format(d, "yyyy-mm-dd"), " ", Dates.format(d, "e, d U yyyy"))
println(DateTime("2024-05-17T09:15:00"))
2024-05-17
2024-05-17 Fri, 17 May 2024
2024-05-17T09:15:00

dateformat"..." builds the format once at compile time, which is faster when parsing many dates.

Date ranges

using Dates

for d in Date(2024, 1, 1):Week(1):Date(2024, 1, 31)
    print(Dates.format(d, "u d"), "  ")
end
println()
mondays = filter(d -> dayofweek(d) == Monday, Date(2024, 7, 1):Day(1):Date(2024, 7, 31))
println(length(mondays), " Mondays in July 2024")
Jan 1  Jan 8  Jan 15  Jan 22  Jan 29
5 Mondays in July 2024

The current time

now() returns the current local DateTime, today() the current Date, and now(UTC) the time in UTC. time() returns seconds since 1970 as a float — see the Unix epoch converter — and unix2datetime converts it.