可以覆盖Ruby中的系统时区吗? [英] Can I override the system timezone in Ruby?

查看:138
本文介绍了可以覆盖Ruby中的系统时区吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ubuntu 12.04 上,我可以看到:

I'm here on Ubuntu 12.04, and I can see:

$ cat /etc/timezone 
America/Phoenix

因此时间将返回一个非UTC区域的时间:

Accordingly Time will return a time with a non-UTC zone:

$ irb
> Time.now
=> 2013-03-27 13:44:49 -0700
> Time.at 0
=> 1969-12-31 17:00:00 -0700

我可以使用 TZ 环境变量

$ TZ=UTC irb
> Time.now
=> 2013-03-27 20:47:19 +0000
> Time.at 0
=> 1970-01-01 00:00:00 +0000

有没有办法通过编程方式在Ruby进程中?

Is there anyway I can make this change programmatically, within a Ruby process?

推荐答案

您还可以通过访问 ENV来设置ruby内的环境变量哈希:

You can also set environment variables from within ruby by accessing the ENV hash:

ENV['TZ'] = 'UTC'
Time.at 0
#=> 1970-01-01 00:00:00 +0000

也看到这个答案:在Ruby中设置时区偏移,它提供了一种写入类似于

also see this answer: Set time zone offset in Ruby, It provides a way to write something like

with_time_zone 'UTC' do
  # do stuff
end

# now TZ is reset to system standard

这篇关于可以覆盖Ruby中的系统时区吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆