From 1c4707c18f97c60b96e43e1233a21d81ef232c11 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 28 Feb 2019 19:31:45 -0600 Subject: [PATCH] Add Comparing DateTime Structs as an elixir til --- README.md | 3 ++- elixir/comparing-datetime-structs.md | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 elixir/comparing-datetime-structs.md diff --git a/README.md b/README.md index a4cc82a..df58eac 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_774 TILs and counting..._ +_775 TILs and counting..._ --- @@ -123,6 +123,7 @@ _774 TILs and counting..._ - [Assert An Exception Is Raised](elixir/assert-an-exception-is-raised.md) - [Binary Representation Of A String](elixir/binary-representation-of-a-string.md) - [Check For A Substring Match](elixir/check-for-a-substring-match.md) +- [Comparing DateTime Structs](elixir/comparing-datetime-structs.md) - [Compute md5 Digest Of A String](elixir/compute-md5-digest-of-a-string.md) - [Counting Records With Ecto](elixir/counting-records-with-ecto.md) - [Create A Date With The Date Sigil](elixir/create-a-date-with-the-date-sigil.md) diff --git a/elixir/comparing-datetime-structs.md b/elixir/comparing-datetime-structs.md new file mode 100644 index 0000000..2b40947 --- /dev/null +++ b/elixir/comparing-datetime-structs.md @@ -0,0 +1,26 @@ +# Comparing DateTime Structs + +> Remember, comparisons in Elixir using ==/2, >/2, structural and based on the DateTime struct fields. For proper comparison +> between datetimes, use the compare/2 function. + +As the [DateTime docs](https://hexdocs.pm/elixir/DateTime.html) say, you'll +want to use [`compare/2`](https://hexdocs.pm/elixir/DateTime.html#compare/2) +in order to accurately compare two `DateTime` structs. + +```elixir +{:ok, older} = DateTime.from_naive(~N[2016-05-24 13:26:08.003], "Etc/UTC") +{:ok, newer} = DateTime.from_naive(~N[2017-11-24 13:26:08.003], "Etc/UTC") + +DateTime.compare(older, newer) +#=> :lt + +DateTime.compare(newer, older) +#=> :gt + +DateTime.compare(newer, newer) +#=> :eq +``` + +When using `compare/2`, you'll get one of `:lt`, `:gt`, or `:eq` as a +result, meaning _less than_, _greater than_, or _equal_ respectively.