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#gm和Time#local和红宝石TZInfo类,特别是TZInfo::Timezone.get和TZInfo::Timezone#period_for_local
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)
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)
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)
now = Time.now
now.in_time_zone('Eastern Time (US & Canada)')
or
now.in_time_zone('Asia/Manila')
Run Code Online (Sandbox Code Playgroud)
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 # 获取新时区的时间