Subject: Date timezone conversion UTC to JST
Date: mar 26 feb 13 05:05:53 +0900
Quoting Soichi I. ([email protected]):
undefined method `in_time_zone’ for #<Date: 2013-02-21
((2456345j,0s,0n),+0s,2299161j)> (NoMethodError)
First of all: the Date class contains only the date (not the
time). You may want to explore the DateTime class instead. But then, I
read from the documentation of Date that:
“All date objects are immutable; hence cannot modify themselves”.
and I expect this to be true for the DateTime class too. If you want
to make time arithmetics, you have to use the Time class, instead.
Then: a Time instance is first and foremost a number of seconds
since the Epoch (1970-01-01 00:00:00 +0000 (UTC)). Thus: an ABSOLUTE
time:
p Time::now.to_i
1361868476
The timezone is an IDEA that your specific process has, and in Unix
systems it is defined by the content of system variable TZ. For
example, the output of:
now=Time::now.to_i
ENV[‘TZ’]=‘UTC’
p Time::at(now)
ENV[‘TZ’]=‘Asia/Tokyo’
p Time::at(now)
is:
2013-02-26 08:50:44 +0000
2013-02-26 17:50:44 +0900
I do not know if you want the date to have the Tokyo timezone set,
while keeping the time to 4:36, or you want to find out what the Tokyo
time was for 4:26 UTC. In the first case, you should do something like:
require ‘time’
ENV[‘TZ’]=‘Asia/Tokyo’
str=‘02/21/2013 4:36:53’
t=Time.strptime(str,"%m/%d/%Y %H:%M:%S")
p t
which gives
2013-02-21 04:36:53 +0900
If the second possibility is true, you should do this, for example:
require ‘time’
str=‘02/21/2013 4:36:53’
ENV[‘TZ’]=‘UTC’
secs=Time.strptime(str,"%m/%d/%Y %H:%M:%S").to_i
ENV[‘TZ’]=‘Asia/Tokyo’
t=Time::at(secs)
p t
which gives
2013-02-21 13:36:53 +0900
Both objects are Tokyo times, as you can see. If you want to deal with
unmutable datetime objects, you can use method Time#to_datetime.
Hope this helps
Carlo