Comparing dates in Elixir

ulisesac4

Ulises Avila

Posted on April 10, 2022

Comparing dates in Elixir

Introduction

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.

Contents

Requirements

  • 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)> DateTime.compare(~U[2022-04-10 04:51:27.626455Z], ~U[2022-03-10 04:51:27.626455Z])
:gt

Enter fullscreen mode Exit fullscreen mode

Example 2

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

iex(2)> Date.compare(~D[2022-04-01], ~D[2022-04-08])
:lt

Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
ulisesac4
Ulises Avila

Posted on April 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related