19  Date and Time

Julia includes a Date and a DateTime type.
To use them, load the Dates module, part of the Julia Base Standard Library

using Dates

The Date and DateTime constructors accept multiple input types.

19.1 String to Date

x = Date("2012-02-14")
2012-02-14
typeof(x)
Date

19.2 String to DateTime

x = DateTime("2012-02-14T15:22:51")
2012-02-14T15:22:51
typeof(x)
DateTime

19.2.1 Format strings

Pass a format string to define parsing:

Date("02-14-2012", "mm-dd-yyyy")
2012-02-14

or, shorter:

Date("02-14-2012", "m-d-y")
2012-02-14
Date("14/2/2012", "dd/mm/yyyy")
2012-02-14
Date("14/2/2012", "d/m/y")
2012-02-14
DateTime("2012-02-14 15:22:51", "Y-m-d H:M:S")
2012-02-14T15:22:51

19.3 Integers to Date

Date(2012, 2, 14)
2012-02-14

19.4 String to DateTime

x = DateTime("2020-12-22T14:29")
2020-12-22T14:29:00
typeof(x)
DateTime

19.5 Integers to DateTime

x = DateTime(2020, 12, 22, 14, 29)
2020-12-22T14:29:00

19.6 Unix epoch seconds to DateTime

unix2datetime(1200000000)
2008-01-10T21:20:00

19.7 Today’s Date with today()

today()
2024-07-12

19.8 DateTime with now()

now()
2024-07-12T19:17:18.596

19.9 Format DateTime

Dates.format(now(), "Y-m-d H:M:S")
"2024-7-12 19:17:18"

19.10 Date operations

Subtract Dates to get intervals:

DOB = Date("1978-03-09")
1978-03-09
Age = today() - DOB
16927 days

19.10.1 Range between Dates

DOB:Day(30):today()
Dates.Date("1978-03-09"):Dates.Day(30):Dates.Date("2024-07-05")
collect(Date("2020-12-15"):Day(1):Date("2020-12-21"))
7-element Vector{Date}:
 2020-12-15
 2020-12-16
 2020-12-17
 2020-12-18
 2020-12-19
 2020-12-20
 2020-12-21

19.11 Period Types

Above, we used a period type Day to define the step size of our Date range.
Julia conveniently includes many period types. Their constructors accept an integer input:

Day(3)
3 days
Month(2)
2 months
Year(6)
6 years
Second(45)
45 seconds
Hour(3)
3 hours
Millisecond(137)
137 milliseconds
Microsecond(512)
512 microseconds

19.12 Resources