Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Time zone in pure ruby (not rails)

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 don't have access to Time.zone, in_time_zone, etc.

I only need to change the timezone of a Time object, E.g. 2014-08-14 21:44:17 +0000 => 2014-08-14 14:44:17 -0700.

First I tried this:

class Time
  def to_pst
    self.utc + Time.zone_offset('PDT')
  end
end

But this changes the actual timestamps and not the zone. I need both time.to_i and time.strftime to work; so I can't change the absolute value of the timestamps.

> t = Time.now
=> 2014-08-14 21:46:20 +0000
> t.to_pst
=> 2014-08-14 14:46:20 UTC
> t.to_i
=> 1408052780
> t.to_pst.to_i
=> 1408027580

gem 'timezone' presents a similar problem.

This solution works but alters global variables and is not thread-safe.

The OS time zone needs to stay UTC.

I simply need a way to change the Time zone on a single Time object. This is a simple problem and it seems like it should have a simple solution! Has anyone found one? Thanks in advance!

like image 215
Ellen Sebastian Avatar asked Aug 14 '14 21:08

Ellen Sebastian


People also ask

How do you change TimeZone in Ruby?

You can do: Time. now + Time. zone_offset("PST") if you: require 'time' in your ruby script. guess, should have done that before commenting.

What is the difference between timestamp and Timestamptz?

TIMESTAMPTZ is the same as TIMESTAMP WITH TIME ZONE : both data types store the UTC offset of the specified time. TIMESTAMP is an alias for DATETIME and SMALLDATETIME .


1 Answers

In Pure Ruby

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

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

like image 70
Sivalingam Avatar answered Nov 02 '22 04:11

Sivalingam