ruby 获取给定时区的时间 [英] ruby get Time in given timezone
问题描述
在 ruby 中,如何获取给定时区的当前时间?我知道与 UTC 的偏移量,并希望使用该偏移量获取时区中的当前时间.
In ruby, how can I get current time in a given timezone? I know the offset from UTC, and want to get the current time in the timezone with that offset.
推荐答案
一个更简单、更轻量级的解决方案:
A simpler, more lightweight solution:
Time.now.getlocal('-08:00')
详细记录此处.
更新 2017.02.17:如果您有一个时区并想将其转换为可以与包含 DST 的 #getlocal 一起使用的偏移量,这是一种方法:
Update 2017.02.17: If you've got a timezone and want to turn that into an offset you can use with #getlocal inclusive of DST, here's one way to do it:
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)
如果您想在 #now
以外的时间执行此操作,您应该研究 Ruby 时间类,特别是 Time#gm
和 Time#local
和 Ruby TZInfo 类,特别是 TZInfo::Timezone.get
和 TZInfo::Timezone#period_for_local
If you want to do this for moments other than #now
, you should study up on the Ruby Time class, particularly Time#gm
and Time#local
, and the Ruby TZInfo classes, particularly TZInfo::Timezone.get
and TZInfo::Timezone#period_for_local
这篇关于ruby 获取给定时区的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!