Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby converting UTC to user's time zone

Tags:

ruby

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 conversion. So this is what I do, but at the end you can see it shows UTC not PST or PDT

  [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 finally to get 10/10/2013 03:10 PM PST How to get that? Note: This is not a rails app.

like image 784
JVK Avatar asked Dec 26 '22 19:12

JVK


1 Answers

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'
like image 188
JVK Avatar answered Jan 04 '23 22:01

JVK