ruby get Time in given timezone

前端 未结 9 1195
情书的邮戳
情书的邮戳 2020-12-28 13:17

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.

9条回答
  •  执念已碎
    2020-12-28 13:52

    For an UTC offset of x hours, the current time can be calculated with the help of ActiveSupport in Rails, as the others said:

    utc_offset = -7
    zone = ActiveSupport::TimeZone[utc_offset].name
    Time.zone = zone 
    Time.zone.now
    

    or instead of the two lines

    DateTime.now.in_time_zone(zone)
    

    Or, if you do not have Rails, one can also use new_offset to convert a locate DateTime to another time zone

    utc_offset = -7
    local = DateTime.now
    local.new_offset(Rational(utc_offset,24))
    

提交回复
热议问题