How to work with with Elixir Time
Functions and the Time struct
The hours, minutes, seconds, and microseconds fields make up the Time struct.
The new/4 function and the T function sigil can be used to create new times.
Syntax
time = ~T[23:00:07.001]
Code example
# prints Hello Worldtime = ~T[23:00:07.001]hour= time.hourIO.inspect hour
Code explanation
-
Line 2: We use the
Tsigil to create our time. -
Line 3: We get the hours from the created time by chaining it to the hour field.
-
Line 4: We use the
IO.inspectto output the result.
This module’s functions operate with the Time struct, just like any other struct that has the same fields as the Time struct, such as NaiveDateTime and DateTime.
In their typespecs, such methods expect Calendar.time/0 (rather than t/0).
Instead of building Time structs from scratch, developers should use the functions supplied by this module as well as those in third-party calendar libraries.
Comparing times
In Elixir, comparisons with ==/2, >/2, /2, and similar operators are structural and dependent on the Time struct fields. We can use the compare/2 function to make a suitable Time comparison.