Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 380
Ken Anderson Avatar asked Sep 15 '16 23:09

Ken Anderson


1 Answers

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.

like image 152
potibas Avatar answered Sep 26 '22 16:09

potibas