ruby get Time in given timezone

前端 未结 9 1193
情书的邮戳
情书的邮戳 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:50

    A simpler, more lightweight solution:

    Time.now.getlocal('-08:00')
    

    Well documented here.

    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)
    

    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

提交回复
热议问题