Change Time zone in pure ruby (not rails)

前端 未结 5 1556
抹茶落季
抹茶落季 2021-02-14 07:04

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:58

    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
    

提交回复
热议问题