1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Comparing DateTime Structs as an elixir til

This commit is contained in:
jbranchaud
2019-02-28 19:31:45 -06:00
parent be0a33d861
commit 1c4707c18f
2 changed files with 28 additions and 1 deletions

View File

@@ -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)

View File

@@ -0,0 +1,26 @@
# Comparing DateTime Structs
> Remember, comparisons in Elixir using ==/2, >/2, </2 and friends are
> 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.