How do I tell if a given NaiveDateTime (plus timezone like "US/Mountain") is in the past in Elixir?

Viewed 176

Suppose I have ndt of type NaiveDateTime and a string tz like "US/Mountain". How can I find out if ndt in tz is in the past?

1 Answers

Elixir doesn't include a timezone database by default, but it does support timezones if you add one. At the time of writing, the easiest way is to use Tzdata, but check the DateTime docs for the latest recommendations.

  1. Add {:tzdata, "~> 1.1"} to mix.exs
  2. Add config :elixir, :time_zone_database, Tzdata.TimeZoneDatabase to config/config.exs
  3. Use DateTime.from_naive!/3 to convert to a timezone-aware DateTime.
  4. Use DateTime.compare/2 to compare the date to now.
~N[2000-01-01 10:10:10]
|> DateTime.from_naive!("US/Mountain")
|> DateTime.compare(DateTime.utc_now())
|> Kernel.==(:lt)

Output:

true

Config example:

# config/config.exs
import Config
config :elixir, :time_zone_database, Tzdata.TimeZoneDatabase
Related