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

레일스로 코딩 배우기

나는 루비가 코딩을 배우기에 좋은 출발점이라고 생각한다 Learn To Program 이라는 책을 읽어보라 https://pine.fm/LearnToProgram/ 물론 어느 programming language 로 시작하든지 코딩을 배우는 것은 인생에서 매우 중요하다고 생각한다 그리고 루비를 배우기에는 레일스가 좋은 출발점이라고 생각한다 지금 시작해보자 rails new app_name cd app_name 레일스의... Continue →