Reputation: 151
I recently added a column to my database called created_at_user_time
(initially had no value) which is supposed to hold a timezone converted created_at timestamp. I made a quick script that was supposed to make the conversions and save it in the new column. However after I finished I noticed that the original time stamps had just been copied into the new one. I decided to investigate in rails console and got the following.
1.9.3p194 :002 > user.time_zone
=> "Central Time (US & Canada)"
1.9.3p194 :003 > test = user.orders.first
1.9.3p194 :004 > test.created_at
=> Wed, 02 Jan 2013 02:02:54 UTC +00:00
1.9.3p194 :006 > newstamp = test.created_at.in_time_zone("#{user.time_zone}")
=> Tue, 01 Jan 2013 20:02:54 CST -06:00
1.9.3p194 :008 > test.created_at_user_time = newstamp
=> Tue, 01 Jan 2013 20:02:54 CST -06:00
#ok, now lets save and check it
1.9.3p194 :009 > test.save
(0.4ms) begin transaction
(0.1ms) commit transaction
=> true
1.9.3p194 :010 > test = user.orders.first
1.9.3p194 :011 > test.created_at_user_time
=> Wed, 02 Jan 2013 02:02:54 UTC +00:00
Does anyone have any ideas as to how to do this correctly?
Upvotes: 0
Views: 360
Reputation: 151
As MiGro pointed out, just using the .in_time_zone
method just changes the way the timestamp is displayed in text and doesn't actually change the value. In order to change the value I get the offset from the converted time value and add it to the original time, thus giving me the ability to group orders (see my previous question Modify created_at in query before grouping by date) by the correct date.
test_order = user.order.first
orig_time = test_order.created_at
conv_time = orig_time.in_time_zone(user.time_zone)
offset = conv_time.utc_offset
order.created_at_in_user_time = orig_time + offset
Upvotes: 0
Reputation: 1511
I would say this will return the same time but with different timezone, but at the end it is till the same timestamp:
newstamp = test.created_at.in_time_zone
Upvotes: 1