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!
You can do: Time. now + Time. zone_offset("PST") if you: require 'time' in your ruby script. guess, should have done that before commenting.
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 .
In Pure Ruby
Time.now.utc.localtime("+05:30")
where +05:30 (IST) is the offset of the particular zone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With