Change Time zone in pure ruby (not rails)

前端 未结 5 1306
暖寄归人
暖寄归人 2021-02-14 07:02

I am building a Sinatra site which has mixed UTC/PST data sources, but will be viewed in PST. So I need a way to easily convert Time objects from UTC to PST. Without Rails, I d

相关标签:
5条回答
  • 2021-02-14 07:43

    Get the current time in utc, then add the offset:

    Time.now.utc + Time.zone_offset('PDT')
    #=> 2015-12-01 18:10:07 UTC
    

    The problem here is that PDT is fixed to -8, PST is fixed to -7 and Pacific Zone (one that adjusts between the two based on time of year and daylight savings) does not exist, for that you likely need ActiveSupport.

    0 讨论(0)
  • 2021-02-14 07:45

    You can use the Time extensions from Active Support outside of Rails:

    require 'active_support/core_ext/time'
    
    t = Time.now
    #=> 2014-08-15 15:38:56 +0200
    
    t.in_time_zone('Pacific Time (US & Canada)')
    #=> Fri, 15 Aug 2014 06:38:56 PDT -07:00
    

    Now you can do

    class Time
      def to_pst
        in_time_zone('Pacific Time (US & Canada)')
      end
    end
    
    t = Time.now
    #=> 2014-08-15 15:42:39 +0200
    
    t.to_i
    #=> 1408110159
    
    t.to_pst
    #=> Fri, 15 Aug 2014 06:42:39 PDT -07:00
    
    t.to_pst.to_i
    #=> 1408110159
    
    # timestamp does not change!
    

    Additionally you might also want the time extensions on Numeric and Date:

    require 'active_support/core_ext/date'
    require 'active_support/core_ext/numeric/time'
    
    2.days.from_now
    #=> 2014-08-17 15:42:39 +0200
    
    0 讨论(0)
  • 2021-02-14 07:53

    I recently did the same thing on an iron.io worker which default time is UTC

    # For generality/testing, only require what you need. 
    require 'active_support/all'  
    
    # Set the Timezone 
    Time.zone = "Asia/Hong_Kong" 
    
    t = Time.zone.now
    #=> 2015-01-20 16:44:58 +0800
    

    For info on the supported Timezones take a look at ActiveSupport http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html

    0 讨论(0)
  • 2021-02-14 07:57

    In Pure Ruby

    Time.now.utc.localtime("+05:30")
    

    where +05:30 (IST) is the offset of the particular zone

    0 讨论(0)
  • 2021-02-14 08:07

    If you don't want to load a ton of libraries, and if you don't mind doing it the poor man's way, and you know your offset is -8 for example, you can subtract 8*3600 seconds to get the new time. For example,

    offset=-8
    t = Time.now + offset * 3600
    

    You'll need to adjust for day light savings time yourself though, also this doesn't change the time zone so %z won't be right.

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