Ruby converting UTC to user's time zone

前端 未结 3 1621
遇见更好的自我
遇见更好的自我 2021-01-06 10:15

I have dstring as saved in UTC. While I have user\'s timezone\'s offset standard_offset What I want to show that date in user\'s timezone after con

相关标签:
3条回答
  • 2021-01-06 10:47

    I added a method in_timezone method in Time class as follows:

    class Time
       require 'tzinfo'
       # tzstring e.g. 'America/Los_Angeles'
       def in_timezone tzstring
         tz = TZInfo::Timezone.get tzstring
         p = tz.period_for_utc self
         e = self + p.utc_offset
         "#{e.strftime("%m/%d/%Y %I:%M %p")} #{p.zone_identifier}"
       end
     end  
    

    How to use it:

    t = Time.parse("2013-11-01T21:19:00Z")  
    t.in_timezone 'America/Los_Angeles'
    
    0 讨论(0)
  • 2021-01-06 11:02
    require 'tzinfo'
    class Time
       def in_timezone(tzstring)
         tz = TZInfo::Timezone.get(tzstring)
         p = tz.period_for_utc(self.utc)
         # puts "#{tzstring} -> utc_offset=#{p.utc_offset},utc_total_offset=#{p.utc_total_offset},p.offset=#{p.offset}"
         e = self.utc + p.utc_total_offset
         "#{e.strftime('%Y-%d-%m %H:%M:%S')} #{p.zone_identifier}"
       end
    end
    
    [Time.parse("2013-10-20T21:19:00Z"), Time.parse("2013-11-20T21:19:00Z")].each do |t|
        puts '=======================================================> ' + t.to_s
        puts "\t" + t.in_timezone('GMT')
        puts "\t" + "------------------"
        puts "\t" + t.in_timezone('Europe/London')
        puts "\t" + t.in_timezone('Europe/Prague')
        puts "\t" + t.in_timezone('Asia/Jerusalem')
    end
    
    0 讨论(0)
  • 2021-01-06 11:03

    Apparently this is an issue with the Ruby standard library.

    Sources:

    http://rubydoc.info/gems/tzinfo/file/README.md

    Note that the local Time returned will have a UTC timezone (local.zone will return "UTC"). This is because the Ruby Time class only supports two timezones: UTC and the current system local timezone.

    http://librelist.com/browser//usp.ruby/2011/9/24/unix-time-and-the-ruby-time-class/

    Modern kernels do not know nor care about timezones. Conversions from UTC to the local timezone (and vice versa) are done in user space[2]. Different processes running concurrently on the same machine do not necessarily share the same local timezone.

    Process timezone

    The "TZ" environment variable controls the timezone for a given process, and thus the timezone attached to a Ruby Time object. If "TZ" is unset, the timezone of the process is implementation-defined.

    As far as I can tell, everything related to time zones that is in Rails was built by the Rails core team. Ruby only handles as much time-related functionality as Unix provides and probably expects the user to handle the reset.

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