Timezones can be tricky to manage and sometimes I just get them wrong - like now...
I had been parsing strings representing local times in Seattle and then storing these without an explicit timezone on a machine which uses UTC by default - so they got stored as that time in UTC (not converted to UTC - the exact time string in UTC.
For example: Fri, 05 Apr 2013 14:24:39 (the local time in Seattle) was stored as Fri, 05 Apr 2013 14:24:39 UTC +00:00 which is 7 hours earlier than it should be.
The easiest way to fix this, that I found is to convert back to a string, strip of any record of a timezone and then parse it back into a time, having temporarily set the TZ environment variable to the correct local timezone.
NOTE that this works on UNIX/Mac OS X systems - not sure about Windows...
puts ENV['TZ'] => nil
puts t => 2013-04-05 14:24:39 UTC
s = t.to_s
puts s => "2013-04-05 14:24:39 UTC"
s.sub!(/\s+UTC/, '')
puts s => "2013-04-05 14:24:39"
ENV['TZ'] = 'US/Pacific'
t1 = Time.parse(s)
ENV['TZ'] = nil
puts t1 => 2013-04-05 14:24:39 -0700
Remember to reset the TZ environment variable back to nil
Be very careful about using gmtime and localtime as these methods operate in place. So ALWAYS make a copy of your time before applying those conversions
t => 2013-04-05 15:25:41 -0700
t1 = t.dup
t.gmtime => 2013-04-05 22:25:41 UTC
t => 2013-04-05 22:25:41 UTC
t1 => 2013-04-05 15:25:41 -0700
A collection of computer systems and programming tips that you may find useful.
Brought to you by Craic Computing LLC, a bioinformatics consulting company.
Friday, April 5, 2013
Subscribe to:
Post Comments (Atom)
1 comment:
Nice blog to read, Thanks for sharing this valuable article.
Online Training for Big Data
best Apache Spark online course
Post a Comment