views:

1534

answers:

2

Javascript on my page saves client UTC offset to the cookie. How do I use this cookie to create a TimeZone and assign it to Time.zone ?

I need something like:

before_filter :set_time_zone

def set_time_zone
  Time.zone = ActiveSupport::TimeZone.new('my timezone', cookies[:timezone])
end

except that the right part of this expression does not work and I'm not sure if I'm going the right way here. Can't get it.

+2  A: 

When I have it stored in my User model it is as simple as this

def set_time_zone
  Time.zone = current_user.time_zone unless current_user.blank?
end

so maybe you could do

def set_time_zone
  Time.zone = cookies[:timezone]
end

That's untested, I've never tried to do it from a cookie, I think it makes more sense to store it in the User model.

railsninja
No, I don't need to store it in the user model.Anyway, what your current_user.time_zone looks like? Is it a String?
snitko
Yes, just using the Rails built in time zone stuff, so for my user in an app it would just be "Sydney"
railsninja
+3  A: 

Here's the working googled answer:

min = cookies[:timezone].to_i
Time.zone = ActiveSupport::TimeZone[-min.minutes]

Just to make it clear, the javascript part:

if(!($.cookie('timezone'))) {
  current_time = new Date();
  $.cookie('timezone', current_time.getTimezoneOffset(), { path: '/', expires: 10 } );
}
snitko