l288
l288

Reputation: 67

Elixir Timezone Comparison for UTC and DateTime Struct

I am trying to compare two datetimes to see if they overlap. However, one is a DateTime struct and the other is a ~U[] time - this is how they come out of the database. I cannot work out how to do this - it would be good if I could compare them both in UTC and also keep the timezone awareness.

The two times I have are: start_datetime_1 = ~U[2022-03-31 11:15:00.000000Z]

and starttime_2 = #DateTime<2022-03-31 11:15:00.000000+01:00 BST Europe/London>

I wanted to do something like: DateTime.compare(start_datetime_1, start_datetime_2 == :gt || :eq)

Any help would be appreciated!

Upvotes: 1

Views: 737

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

~U[2022-03-31 11:15:00.000000Z] is the same DateTime but in UTC. A sigil ~U[] is just syntactic sugar.

You can do a comparison with DateTime.compare/2 out of the box. It understands timezones.

DateTime.compare(start_datetime_1, start_datetime_2) in [:gt, :eq]

Upvotes: 6

Related Questions