DEV Community

Ulises Avila
Ulises Avila

Posted on • Originally published at ulisesavila.com on

3 3

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.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay