Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/65890851/how-do-i-tell-if-a-given-naivedatetime-plus-timezone-like-us-mountain-is-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Elixir doesn't include a timezone database by default, but it does support timezones if you add one. The easiest way is to use Tzdata.

  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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...