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

前端 未结 13 2404
感情败类
感情败类 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条回答
  •  温柔的废话
    2020-12-30 22:20

    You don't explicitly say how you get the actual variable but since you mention the Time class so I'll assume you got the time using that and I'll refer to that in my answer

    The timezone is actually part of the Time class (in your case the timezone is shown as UTC). Time.now will return the offset from UTC as part of the Time.now response.

    >> local = Time.now
    => 2012-08-13 08:36:50 +0000
    >> local.hour
    => 8
    >> local.min
    => 36
    >> 
    


    ... in this case I happen to be in the same timezone as GMT

    Converting between timezones

    The easiest way that I've found is to change the offset using '+/-HH:MM' format to the getlocal method. Let's pretend I want to convert between the time in Dublin and the time in New York

    ?> dublin = Time.now
    => 2012-08-13 08:36:50 +0000
    >> new_york = dublin + Time.zone_offset('EST')
    => 2012-08-13 08:36:50 +0000
    >> dublin.hour
    => 8
    >> new_york.hour
    => 3
    

    Assuming that 'EST' is the name of the Timezone for New York, as Dan points out sometimes 'EDT' is the correct TZ.

提交回复
热议问题