Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails seems to be creating objects in wrong time zone for created_at, updated_at values

I just created a new object using a form and its updated_at and created_at values are

created_at: "2013-04-25 03:22:19", updated_at: "2013-04-25 03:22:19",

However that is ~7 hours ahead of where I am (PST).

Time.now.to_s
 => "2013-04-24 20:23:12 -0700" 

How can I make sure the time zone is consistent with wherever a user is creating it from?

like image 864
user1436111 Avatar asked Apr 25 '13 03:04

user1436111


1 Answers

Your created_at and updated_at values are written from your server to the database, so they will always be in your server's or application's time zone. By the time the server processes the form data and saves to your database, it has no knowledge of the browser's time zone.

You can set a Rails time zone using config.time_zone, as @lulalala suggested.

It sounds like you're interested in displaying times to your users in their native time zones. You have two options for this:

  • Ask your user for a time zone on signup (or assign a default one and allow users to edit it)

  • Detect time zone using javascript and report back to your server (http://josephscott.org/archives/2009/08/detecting-client-side-time-zone-offset-via-javascript/) - not guaranteed to be correct

Once you have the time zone saved as a user attribute, you can display your times to your users like this:

Model.created_at.in_time_zone(@current_user.time_zone)
like image 104
mchail Avatar answered Sep 22 '22 07:09

mchail