In the previous post, we present higher-level types: Range, Keyword Lists, and MapSet. Let’s see what Elixir offers in handling Dates and Time. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.
Data Type Or Struct
Elixir does not have special data types for handling dates and times. For that, it uses Structs. We will discuss Structs in one of the following posts. This is a prevalent pattern in Elixir. Elixir is extendable, which gives developers great flexibility. So we have the following Structs that help us in handling dates and times:
Additionally, Elixir has modules that support those Structs. Modules have handy functions that manipulate appropriate Struct.
In Object-Oriented Language we have Classes with attributes and methods, In Elixir we have Modules that operate on Structs.
Elixir offers a sigil that helps us to create appropriate Struct for Date and Time. For Date Struct, we use
~D. Date Struct has four attributes: day, month, year, calendar, and __struct__. __struct__ returns the name of Date Struct. There is also a Date module. Sigil accepts the date string format defined in
Calendar.ISO the module.
Time Struct could be created with Time Sigil, ~T. Struct has microsecond, second, minute, hour, calendar, and __struct__ attributes. __struct__ returns the name of Struct, which is Time. There is a Time module. Sigil accepts the date string defined in the Calendar.ISO module.
This Struct is combining Date and Time but without timezone. In the following image, you can explore NaiveDateTime features:
DateTime Struct does not have a sigil, and it is created using DateTime Module function from_naive, where parameters are NaiveDateTime and Time Zone. DateTime adds to NaiveDateTime Time Zone feature:
Note that when we tried to use different time zone from “Etc/UTC” we got an error. To use world time zones, we need to set up in the Elixir project Time Zone Database. For that, we need Module Tzdata that is not part of Elixir and needs to be included in the project as dependencies. As we will discuss how to set up the Elixir project via Mix, we will explain using the World Time Zone Database after explaining the Mix project.
All modules have
add methods that help you in time travel. For example here is how to go two days into the future and past:
- Elixir is using Struct and Modules to handle date and time.
- There is no dedicated data type.
- date and time could be created using sigils or DateTime module function
- All modules have
addmethod for Date and Time Calendar arithmetic.