Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

User TimeZone in datetime_select tag

I have to get a user input for time in my form. I am using the datetime_select tag.

Now the problem is that the user inputs the time in his/her local timezone but the database saves this local time as a UTC time.

ex: The user is in Asia/Kolkata timezone and enters 8:00 PM. But this gets saved as 8:00 PM UTC in the database.

I have tried using 'datetime_local_field' but that also gives the same error.

I have also tried using a before_save callback to convert timezones but since the form already takes in the time in UTC, the callback does not perform any timezone conversion.

Is there any method to get time from the user in his/her local timezone (since any user will enter the time in his/her local timezone only) and then tell rails that this is in the users local timezone and not UTC.

1 Answer

Brandon Barrette
Brandon Barrette
20,485 Points

So the issue here is that you want the time to be saved the same in the database for comparison sake, then change the time according to the specific user. You wouldn't want one user's timestamps to be Eastern time and one to be Pacific time (for the US) because then no real comparisons could be done. Instead store them as UTC/GMT so it's consistent, then convert them to the time zone of the specific user.

I suggest you have your users pick a time zone, then can do conversion from there. This article is an interesting read:

http://danilenko.org/2012/7/6/rails_timezones/

Thanks. For now I implemented this by subtracting the time zone offset of a fixed timezone from the user entered data. I'll extend this to all timezones by adding javascript to get the user timezone and then compensating the user entered time with this data.