Comparing dates in Elixir

Written by Ulises Avila in elixir at 08 April 2022


Comparing dates is a common procedure in day to day jobs. Whether you need them to trigger future, or past jobs you will need to know how to do it in Elixir.



  • none

Comparing Dates

To acomplish this task, you will use the .compare/2 method. Which exists in both Date and DateTime structs.

Upon success compare, the method will return any of the next atoms :lt | :eq | :gt.

Example 1

A DateTime utc format comparison where the first element is greater than the second.

iex(5)>[2022-04-10 04:51:27.626455Z], ~U[2022-03-10 04:51:27.626455Z])

Example 2

A Date comparison where the first element is lesser than the second.

iex(2)>[2022-04-01], ~D[2022-04-08])

After thoughts

After using other tools in differents environments like date-fns or moment in javascript. I find refreshing the method used in this posting, instead of relying on a specific method to assert a question, ie isAfter from date-fns, here you get exactly the result of the comparison.