Date timezone conversion UTC to JST

Ruby 1.9.3

I would like to convert String datetime to Datetime object in a specific

I have

str = ‘02/21/2013 4:36:53’


d = Date.strptime(str, “%m/%d/%Y %H:%M:%S”)

can parse the string. And this time object is in UTC. I need to convert
it to Asia/Tokyo


p d.in_time_zone(‘Asia/Tokyo’)

gives an error,

undefined method `in_time_zone’ for #<Date: 2013-02-21
((2456345j,0s,0n),+0s,2299161j)> (NoMethodError)

I believe the original string has no indication of time zone. So ruby
cannot tell from which time zone it needs to be converted…? but I am
not sure.

Can anyone help me out?


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

p Time::now.to_i

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:

p Time::at(now)
p Time::at(now)


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’
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’
secs=Time.strptime(str,"%m/%d/%Y %H:%M:%S").to_i
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


thanks for such a thorough explanation.
It helped me a lot!