Ruby on rails converts to users timezone

I have all the timezone information I need, and it stores all the information correctly according to this railscast . Everything works fine for all common purposes like displaying the time in a table, however I am wondering how I can convert the following to a current_users

saved timezone.

I have the total number of calls hourly:

Calls.count(:group => DATE_PART('hour', start_time), 
            :conditions => ["start_time BETWEEN ? AND ?", start, finish]

      

This request uses all calls that were made within the hour between the start and end times. The only thing is that it returns the time in the database, which is stored as UTC. I wrote my own conversion method with Time.now.utc_offset

, but realized that this would not work. What would be a good way to compare the users saved time_zone

with what is coming from the database and add utc_offset

.

time_zone

stored as a string in the Eastern Time (US and Canada) database .

What is the best way to figure this out, I can change to store the user offset in the database, but before I go do this, I would rather if there is an easier way.

Edit
To be more clear, the query returns a hash of hours and a counter. For example:

                Hour                       Count
                "5"                          20
                "6"                          15
                "7"                          35
                ...                          ...

      

The hour is returned as UTC offset hour, I need to convert that digit to the users timezone, so for example if it is 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 it out quite simply. The first thing you want to do is set the Time object to the users' current time zone. So:

Time.zone = @current_user.time_zone
=> "Eastern Time (US & Canada)

      

Then add the current user offset to the "Hour" inside the hash

hour + Time.now.in_time_zone.utc_offset / 3600

      

Pretty self-explanatory, but this gets the time in the zone you set earlier and finds the UTC offset in seconds, so we're dividing by 3600.

+2


source to share


2 answers


Does it help?

t = TimeZone["Eastern Time (US & Canada)"]
t.utc_to_local(DateTime.now) #gives the local time

      



Whoever posted in front of me deleted their answer (it was much better than my answer). If he returns his answer, I'll take it with me again.

+4


source


scope :opened, where("date > '#{Time.now.in_time_zone}'")
scope :closed, where("date < '#{Time.now.in_time_zone}'")

      



0


source







All Articles