Ruby converts UTC to user timezone

I have dstringas saved in UTC. Although I have a user’s timezone offset standard_offset I want to display this date in the user’s timezone after conversion. So this is what I do, but in the end you see that it shows UTCnot PSTorPDT

  [64] pry> dstring
  => "2013-10-31T23:10:50Z"
  [65] pry> standard_offset = -8
  => -8
  [66] pry> e = Time.parse(dstring) + (standard_offset * 3600)
  => 2013-10-31 15:10:50 UTC
  [67] pry> e.strftime("%m/%m/%Y %I:%M %p %Z")
  => "10/10/2013 03:10 PM UTC"

I expect to finally receive 10/10/2013 03:10 PM PSTHow to get it? Note. This is not a rails app.

+4
source share
3 answers

I added the method in_timezoneto the class Timeas 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'
+10
source

This seems to be a problem with the standard Ruby library.

Sources:

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

, , UTC (local.zone "UTC" ). , Ruby Time : UTC .

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

. UTC ( ) [2]. , , .

"TZ" , , , Ruby Time. "TZ" , .

, , , Rails, Rails. Ruby , Unix, , , , reset.

+2
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
-2
source

All Articles