0

I've looked at a few StackOverflow questions but none of them seem to crack the case.

My time for example is :

2012-04-19 08:42:00 +0200

This is what is inputed through the form. But everything is displayed relative to what timezone it is in. So because the computer works in UTC, this time after it is saved comes out as :

Wed, 18 Apr 2012 23:42:00 PDT -07:00

How do I keep the same time, but just change the zone?

Trip
  • 26,756
  • 46
  • 158
  • 277

2 Answers2

2

I think the method Time.use_zone might help you. In the app I'm working one we wanted times to be interpreted according to the current user's time zone. Our User class was given a time_zone attribute, which is just a valid ActiveSupport::TimeZone string, and we created an around_filter as follows:

class ApplicationController < ActionController::Base

  around_filter :activate_user_time_zone

  def activate_user_time_zone
    return yield unless current_user # nothing to do if no user logged in
    return yield unless current_user.time_zone && ActiveSupport::TimeZone[current_user.time_zone] # nothing to do if no user zone or zone is incorrect
    Time.use_zone(ActiveSupport::TimeZone[current_user.time_zone]) do
      yield
    end
 end

end

Basically, this will execute the code in the controller action as if it was in the current user's time zone.

tsherif
  • 11,502
  • 4
  • 29
  • 27
1

I have same requirement. Please check this and this link also

Alternatively

"2012-04-19 08:42:00 +0200".to_time.strftime("%c").to_datetime
Community
  • 1
  • 1
Amit Patel
  • 15,609
  • 18
  • 68
  • 106