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.now.in_time_zone in any Rails file it shows the time as set it up on
config.time_zone = 'Central Time (US & Canada)'
..and such friendly names here you can list up when
rake time:zones:all on command line.
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>
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)
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.