[英]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? Elixir或Erlang有没有办法打印出当前时区的名称? I know that I can get the local time in Elixir by calling the Erlang Calendar module. 我知道我可以通过调用Erlang Calendar模块获取Elixir的当地时间。
:calendar.local_time
and I can get the current time in UTC in Elixir by using the Calendar package: 我可以使用日历包获取Elixir中UTC的当前时间:
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. 我想以UTC格式存储我的日期,但是在当地时区显示它们。 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. 我居住的地方,当前时区被称为“MST7MDT”(当DST没有生效时为“MST”),但我不想将这些字符串硬编码到我的程序中。
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? 有没有办法让Elixir告诉我,我当前的时区是“MST7MDT”,那么我可以使用Calendar.DateTime函数正确格式化我的DateTimes?
I think the best approach would be to just use :calendar.universal_time_to_local_time
when displaying the dates to your end user. 我认为最好的方法是在向最终用户显示日期时使用:calendar.universal_time_to_local_time
。
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: 但是如果你真的需要获得系统的当前时区,并且它是一个类Unix系统,你总是可以这样做:
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. 似乎没有任何与java.util.TimeZone.getDefault()
相当的东西。
我认为实际上没有正式的方法如何在erlang中将本地时区信息作为字符串获取,但您可以尝试使用qdate库
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.