Reputation: 1026
I have all the time zone information that is needed and it saves all of the information correctly according to this railscast. Everything works great for all the normal purposes like displaying time's in a table, however I am wondering how I can convert the following to the current_users
saved time zone.
I have a finds the total number of calls hourly:
Calls.count(:group => DATE_PART('hour', start_time),
:conditions => ["start_time BETWEEN ? AND ?", start, finish]
This query pulls in all all the calls that were made in an hour between the start and finish time. The only thing is that it's pulling back the time in the database which is stored as UTC. I wrote my own little conversion method with Time.now.utc_offset
but realized that wouldn't work. What would be a good way to compare the users saved time_zone
with what is coming down from the database and add the utc_offset
.
The time_zone
is stored as a string in the database Eastern Time (US & Canada).
What is the best way of figuring this out, I can change to save the user's offset in the database but before I go do that I would rather see if there is an easier way.
Edit
To be more clear, the query returns a hash of hours and the count. So for example:
Hour Count
"5" 20
"6" 15
"7" 35
... ...
The hour is coming back as a UTC offset hour, I need to convert that digit to the users time zone, so for example, if it's Eastern Time (US and Canada) you loop through the hash and add -4 to the hour.
Edit 2
Thanks to Andy I was able to figure this out pretty simply. The first thing you want to do is set the Time object to the current users Time zone. So:
Time.zone = @current_user.time_zone
=> "Eastern Time (US & Canada)
Then Add the current user's offset to the "Hour" inside the hash
hour + Time.now.in_time_zone.utc_offset / 3600
Pretty self explanatory, but that gets the time of the zone you set earlier, and finds the UTC offset in seconds which is why we divide by 3600.
Upvotes: 2
Views: 2217
Reputation: 2280
scope :opened, where("date > '#{Time.now.in_time_zone}'")
scope :closed, where("date < '#{Time.now.in_time_zone}'")
Upvotes: 0
Reputation: 31761
Does this help?
t = TimeZone["Eastern Time (US & Canada)"]
t.utc_to_local(DateTime.now) #gives the local time
Whoever posted before me deleted his answer (it was much better than my answer). If he brings his answer back I'll take mine down again.
Upvotes: 4