How To Handle Date And Time In Elixir? — Tentamen Software Testing Blog

Image for post
Image for post
Elixir Date Struct And Module

TL;DR

Data Type Or Struct

  • Date
  • Time
  • NaiveDateTime
  • DateTime

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.

Date

Time

Image for post
Image for post
Elixir Time Struct And 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.

NaiveDateTime

Image for post
Image for post
Elixir NaiveDateTime

DateTime

Image for post
Image for post
Elixir DateTime Struct And Module

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.

Arithmetic

Image for post
Image for post
Elixir Time Arithmetic

Remember

  • There is no dedicated data type.
  • date and time could be created using sigils or DateTime module function
  • All modules have add method for Date and Time Calendar arithmetic.

Originally published at https://blog.tentamen.eu on October 8, 2020.

Written by

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store