How do I change the zone offset for a time in Ruby on Rails?

前端 未结 13 2406
感情败类
感情败类 2020-12-30 22:03

I have a variable foo that contains a time, lets say 4pm today, but the zone offset is wrong, i.e. it is in the wrong time zone. How do I change the time zone?

When

13条回答
  •  旧时难觅i
    2020-12-30 22:09

    This takes advantage of the fact that Time#asctime doesn't include the zone.

    Given a time:

    >> time = Time.now
    => 2013-03-13 13:01:48 -0500
    

    Force it to another zone (this returns an ActiveSupport::TimeWithZone):

    >> ActiveSupport::TimeZone['US/Pacific'].parse(time.asctime)
    => Wed, 13 Mar 2013 13:01:48 PDT -07:00
    

    Note that the original zone is ignored completely. If I convert the original time to utc, the result will be different:

    >> ActiveSupport::TimeZone['US/Pacific'].parse(time.getutc.asctime)
    => Wed, 13 Mar 2013 18:01:48 PDT -07:00
    

    You can use to_time or to_datetime on the result to get a corresponding Time or DateTime.

    This question uses an interesting approach with DateTime#change to set the tz offset. (Remember that ActiveSupport makes it easy to convert between Time and DateTime.) The downside is that there's no DST detection; you have to do that manually by using TZInfo's current_period.

提交回复
热议问题