ruby在给定时区内得到时间

ash*_*eta 31 ruby timezone

在ruby中,我如何获得给定时区的当前时间?我知道从UTC的偏移量,并希望获得具有该偏移量的时区中的当前时间.

Jim*_*yer 37

更简单,更轻量级的解决方案:

Time.now.getlocal('-08:00')
Run Code Online (Sandbox Code Playgroud)

有据可查这里.

更新2017.02.17:如果你有一个时区并希望将其转换为偏移量,你可以使用包含DST的#getlocal,这是一种方法:

require 'tzinfo'

timezone_name = 'US/Pacific'

timezone = TZInfo::Timezone.get(timezone_name)
offset_in_hours = timezone.current_period.utc_total_offset_rational.numerator
offset = '%+.2d:00' % offset_in_hours

Time.now.getlocal(offset)
Run Code Online (Sandbox Code Playgroud)

如果你想比其他时刻做到这一点#now,你应该在学习了Ruby的时间类,特别是Time#gmTime#local红宝石TZInfo类,特别是TZInfo::Timezone.getTZInfo::Timezone#period_for_local

  • chadoh的回答如下.这里的问题是没有考虑夏令时. (3认同)

gle*_*man 15

我使用ActiveSupport gem:

require 'active_support/time'
my_offset = 3600 * -8  # US Pacific

# find the zone with that offset
zone_name = ActiveSupport::TimeZone::MAPPING.keys.find do |name|
  ActiveSupport::TimeZone[name].utc_offset == my_offset
end
zone = ActiveSupport::TimeZone[zone_name]

time_locally = Time.now
time_in_zone = zone.at(time_locally)

p time_locally.rfc822   # => "Fri, 28 May 2010 09:51:10 -0400"
p time_in_zone.rfc822   # => "Fri, 28 May 2010 06:51:10 -0700"
Run Code Online (Sandbox Code Playgroud)

  • 当我安装active_support gem时,我需要'active_support/time'才能让你的示例正常工作. (2认同)

0x4*_*672 11

对于x小时的UTC偏移量,可以在Rails中的ActiveSupport的帮助下计算当前时间,其他人说:

utc_offset = -7
zone = ActiveSupport::TimeZone[utc_offset].name
Time.zone = zone 
Time.zone.now
Run Code Online (Sandbox Code Playgroud)

或者代替两条线

DateTime.now.in_time_zone(zone)
Run Code Online (Sandbox Code Playgroud)

或者,如果您没有Rails,还可以使用new_offset将定位DateTime转换为另一个时区

utc_offset = -7
local = DateTime.now
local.new_offset(Rational(utc_offset,24))
Run Code Online (Sandbox Code Playgroud)


cha*_*doh 5

gem install tzinfo
Run Code Online (Sandbox Code Playgroud)

然后

require 'tzinfo'

tz = TZInfo::Timezone.get('US/Pacific')
Time.now.getlocal(tz.current_period.offset.utc_total_offset)
Run Code Online (Sandbox Code Playgroud)


jpw*_*ynn 5

now = Time.now
now.in_time_zone('Eastern Time (US & Canada)') 
or 
now.in_time_zone('Asia/Manila') 
Run Code Online (Sandbox Code Playgroud)

  • `in_time_zone` 需要 ActiveSupport 的 `DateAndTime::Zones` 扩展。 (3认同)

ste*_*enr -4

只需添加或减去适当的秒数:

>> utc = Time.utc(2009,5,28,10,1) # 给定 utc 时间
=> 2009 年 5 月 28 日星期四 10:01:00 世界标准时间
>> bst_offset_in_mins = 60 # 和另一个时区的偏移量
=> 60
>> bst = t + (bst_offset_in_mins * 60) # 只需添加以秒为单位的偏移量
=> Thu May 28 11:01:00 UTC 2009 # 获取新时区的时间

  • 注意:您仍然返回 UTC 时间,它只是被偏移了,如果您尝试比较时间,这将导致各种奇怪的情况。对此的一个很好的测试是两者是否仍然相等。 (2认同)