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!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

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

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay