Sterling Rose Design Blog

Rendering datetime in a user's timezone

6 Comments
Tags: Rails date and time
We recently had a client who wanted to account for a user’s time zone when they entered dates for various fields. For example, if a user were to input a new bill, the bill entry date should default to the current date. Time.now is what we had been using, but that would only give the right date if you were on the correct side of the magic UTC dividing line.

The solution to this problem involved 1) storing a user’s time zone in a string field in the User model, and 2) adjusting Time.now for that time zone.

For part 1, we used Rails’ built-in time_zone_select method:

<%= form.label :time_zone, "Time Zone" %>
<%= time_zone_select :time_zone, @user.time_zone, nil, :default => 
  "Pacific Time (US & Canada)" %>


For part 2, the solution was to add a method to the User model to get the user’s current date:

def my_date(input=Time.now)
  Time.zone = time_zone
  d = input.to_datetime
  user_time_zone_date = Time.zone.utc_to_local(d)
  user_time_zone_date
end


This leaves the door open for you to pass in any time at all, and have it parsed for the user’s current date.
Comments

That’s exactly what I was looking for!Your article is much useful for my paper, thanks a lot
dissertation example

I’ll use this method too. I hope it’ll help to make my work easer.

Wow! Great idea! I always have problems with the time zones

I discovered numerous fascinating stuff in your blog particularly the on going conversation. From the tons of comments on your articles.Great work.Keep it up.

I discovered numerous fascinating stuff in your blog particularly the on going conversation. From the tons of comments on your articles.Great work.Keep it up.

Well it is not such a big deal to make a whole post.


Leave a Comment











Copyright 2007-2012, Sterling Rose Design. All rights reserved.