Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

time
elixir
communitycreator

How to work with with Elixir Time

Chinweuba Elijah Azubuike

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 World
time = ~T[23:00:07.001]
hour= time.hour
IO.inspect hour
Making up the Time struct

Code explanation

  • Line 2: We use the T sigil 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.inspect to 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.

RELATED TAGS

time
elixir
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring