I’ve found an issue when trying to use the time_ago_in_words and
distance_of_time_in_words from action view’s date_helper.rb
Using SQL Server, I have a datetime column that gets returned as:
“2007/02/21 09:54:00”. When I pass this to time_ago_in_words (which
just passes on to distance_of_time_in_words) it miscalculates the
difference as “9 hours” (…um yeah, it was 10:54 when I tested this),
when the difference should have been “1 hour”. So I fired up script/
console to see what was going on…
setting up to use the date_helpers…
helper.extend ApplicationHelper
=> #Object:0x391bfd8
my record from SQL server returns time like this…
t.updated_on
=> "“2007/02/20 15:09:04"”t.updated_on.class
=> String
so make a string in same format that represents ~1 hour ago…
nine_54 = “2007/02/21 09:54:00”
=> “2007/02/21 09:54:00”
see what the helper gives me… (about 1 hour difference from
Time.now)
helper.time_ago_in_words(nine_54)
=> “about 9 hours”
looking at date_helper.rb I see that parameters passed in are called
with to_time method…
nine_54.to_time
=> Wed Feb 21 09:54:00 UTC 2007Time.now.to_time
=> Wed Feb 21 11:04:34 Pacific Standard Time 2007
A ha! So we’re off by the difference in time zones between PST and
UTC (GMT?). So poking around a bit more…
Time.parse(nine_54)
=> Wed Feb 21 09:54:00 Pacific Standard Time 2007
Success!
So in my view, all I have to do to get the correct time is use
time_ago_in_words(Time.parse(updated_on)) for it to work.
So is this a bug? It is correctly parsing the difference in the times
when considering the time zone differences, but what about the
difference between Time.parse and to_time? Shouldn’t these return the
same answer?
What about the datetime from SQL server? Is the value in the db stored
with tzone info, or is to_time just assuming a defualt tzone of UTC?