LearningRoR
LearningRoR

Reputation: 27192

Invalid argument to TimeZone?

I'm trying to make my users Time zone be the current Time zone of my application so everything they interact will be by it. I run into an ArgumentError for my method inside of my ApplicationController though.

application_controller.rb

before_filter :set_user_time_zone

private

def set_user_time_zone
  if signed_in?
   Time.zone = Time.now.in_time_zone(current_user.time_zone)
  end
end

Notes: current_user is a Devise Helper and my User model as a :time_zone column.

Than the error:

invalid argument to TimeZone[]: Mon, 20 Aug 2012 13:16:20 JST +09:00

I don't know where to go from here. Any ideas on how to correct this?

Thanks.

UPDATE

class Price
  attr_accessible :date
  def self.today
    where(:date => Date.today)
  end
end

If my method does:

def set_user_time_zone
  if signed_in?
    Time.zone = current_user.time_zone
  end
end

The problem I have my times are like this:

 Time.now = US EAST- 2012-08-22 21:17:03 -0400 
 Time.zone = TOKYO - (GMT+09:00) Tokyo 
 Time.zone.now 2012-08-23 10:17:03 +0900

Which means all of my Date methods go by

Time.now = US EAST- 2012-08-22 21:17:03 -0400

when it should be

Time.zone.now 2012-08-23 10:17:03 +0900

How can I get it to the latter?

Upvotes: 6

Views: 4330

Answers (2)

tomgi
tomgi

Reputation: 1422

Time.now.in_time_zone(current_user.time_zone) returns instance of TimeWithZone class, but Time#zone= expects to get something that can be converted to TimeZone.

Assuming you store TimeZone identifiers in your :time_zone column (“Eastern Time (US & Canada)”, "Hawaii", etc.) you can simply do

Time.zone = current_user.time_zone

Upvotes: 3

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24617

Time#zone= method accepts only these params:

  • A Rails TimeZone object.

  • An identifier for a Rails TimeZone object (e.g., “Eastern Time (US & Canada)”, -5.hours).

  • A TZInfo::Timezone object.

  • An identifier for a TZInfo::Timezone object (e.g., “America/New_York”).

So you should pass something from this list

Upvotes: 3

Related Questions