How do I calculate the offset, in hours, of a given timezone from UTC in ruby?

前端 未结 1 1634
迷失自我
迷失自我 2020-12-23 18:14

I need to calculate the offset, in hours, of a given timezone from UTC in Ruby. This line of code had been working for me, or so I thought:

offset_in_hours =         


        
相关标签:
1条回答
  • 2020-12-23 19:15

    Yes, use TZInfo like this:

    require 'tzinfo'
    tz = TZInfo::Timezone.get('America/Los_Angeles')
    

    To get the current period:

    current = tz.current_period
    

    To find out if daylight savings time is active:

    current.dst?
    #=> true
    

    To get the base offset of the timezone from UTC in seconds:

    current.utc_offset
    #=> -28800 which is -8 hours; this does NOT include daylight savings
    

    To get the daylight savings offset from standard time:

    current.std_offset
    #=> 3600 which is 1 hour; this is because right now we're in daylight savings
    

    To get the total offset from UTC:

    current.utc_total_offset
    #=> -25200 which is -7 hours
    

    The total offset from UTC is equal to utc_offset + std_offset.

    This is the offset from the local time where daylight savings is in effect, in seconds.

    0 讨论(0)
提交回复
热议问题