简体   繁体   中英

How do I infer the current timezone in Elixir or Erlang?

Is there a way in Elixir or Erlang to print out the name of current timezone? I know that I can get the local time in Elixir by calling the Erlang Calendar module.

:calendar.local_time

and I can get the current time in UTC in Elixir by using the Calendar package:

Calendar.DateTime.now_utc()

However, neither of these packages provide me with a method that will return the name of the current time zone. I would like to store my dates in UTC but display them in the local time zone. Where I live, the current timezone is called "MST7MDT" (and "MST" when DST is not in effect) but I don't want to hard code those strings into my program.

Is there a way to have Elixir tell me that my current timezone is "MST7MDT", so I can then use the Calendar.DateTime functions to format my DateTimes correctly?

I think the best approach would be to just use :calendar.universal_time_to_local_time when displaying the dates to your end user.

But if you really need to get the current time zone of the system, and it's a Unix-like system, you can always do something like:

def get_timezone() do
  {zone, result} = System.cmd("date", ["+%Z"])
  if result == 0, do: String.trim(zone)
end

Not the most elegant solution, but works. There doesn't seem to be anything equivalent to java.util.TimeZone.getDefault() available.

我认为实际上没有正式的方法如何在erlang中将本地时区信息作为字符串获取,但您可以尝试使用qdate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM