local time in Rails app

This is what I found:

when I did Time.now in Ruby, it returns my local time (my system time, I should say).
when I did Time.zone.now or Time.now.in_time_zone in any Rails file it shows the time as set it up on config/application.rb:

config.time_zone = 'Central Time (US & Canada)'

..and such friendly names here you can list up when rake time:zones:all on command line.

http://www.ruby-doc.org/core-2.1.5/Time.html
http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html

Anyway, when a user access my app it doesn’t show their local time, but the time as set up on config/application.rb. And for local use (rails server) it’s enough to call Time.now for our current time, but this is quite meaningless because when you deploy on heroku, its system uses UTC time.

And fyi Rails saves it as UTC time in the database also… even though it returns local time as it has on config file.

You still can get the time zone from the user (for example, on user registration screen) and save, to let the app use it like this:

<div class="field">
  <%= f.label :time_zone %><br />
  <%= f.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones %>
</div>
Time.use_zone(current_user.time_zone)

However, I still wanted to find a way without saving time zone info in the database… (I needed current time for view and the form only)

https://github.com/basecamp/local_time

First, local_time gem shows browser local time somehow. It uses JS, and it changes html after getting UTC on the html tag. So you cannot use this as default value on any form (I wanted to use it on the datetime_select of “task” form, by the way. and tried Time.parse without anything good, because it was found as JS, after the page all loaded, you know)

This didn’t work:

<% form_for @task do |f| %>
  <%= f.datetime_select :done_at, default: Time.parse(local_time(Time.now)) %>

Finally I ended up to find geocoder gem. I didn’t apply it yet, but it says this GeoCoder can return time zone by ip address of request.

http://www.rubydoc.info/gems/geocoder/1.2.6/frames#Request_Geocoding_by_IP_Address

 
5
Kudos
 
5
Kudos

Now read this

Put comments under a post

How-to from “just a post” to “a post with comments under it” page. We will have: comment creation form in the post show page list of all comments after. We need: nested resources (need routing supports that generated url) model-backed... Continue →