In my Rails application I would like to store the last_login
time of a user in a database. Then I would like to display the last_login
time to user based on his local time (i.e. it should be X if user is in Canada now, and Y if user is in Australia now).
Question 1
How would you recommend to handle the time difference ? Should I store in database the last_login
tra开发者_高级运维nslated to UTC, and when displaying translate it again to the local time, or is there a better method ?
Question 2
How could I identify the local timezone for displaying the last_login
?
I think you are right about storing last_login_at
in UTC (or whatever server time is). It will be stored in that time by default. Then you can convert it to user local time:
user.last_login_at.in_time_zone('Eastern Time (US & Canada)')
In Rails Api you can find more about timezones and about time with zone.
To determine user timezone you can use some GeoIP tool, for example this one (follow description there). But it's not 100% accurate detection. The most reliable way to ask user select his timezone when he signing up.
To collect all timezones you can run:
ActiveSupport::TimeZone.all.map(&:name)
精彩评论