user464180
user464180

Reputation: 1359

RoR: Parse datetime UTC string into timezone specific

Datetimes are being stored in MySQL as UTC.

In my app I've set: config.time_zone = 'UTC'

In my application_controller I set the users selected timezone:

around_filter :user_time_zone, :if => :current_user

def user_time_zone(&block)
  Time.use_zone(current_user.time_zone, &block)
end

I can confirm this works by <%= Time.zone.now%> as it returns the user's set timezone

I then do a select query to grab the datetime field, and present it to the user as part of an array.

In my view, I have:

<%= Time.zone.parse(item[1]).strftime("%m/%d/%Y %I:%M %p") %>

which just outputs the datetime as-is (UTC), not in the user's specific time zone.

What do I need to change in order for the date and time to display correctly in the user's desired timezone?

Thanks for your time and assistance.

Edit:

Per Benjamin's suggestions, I had to modify it slightly to get it to work (was getting the same error) - Time.strptime(item[1], '%Y-%m-%d %H:%M:%S').in_time_zone(Time.zone) but 2 issues still remain.

1 - the original datetime is: 2013-07-25 22:27:50, but what is displayed is: 2013-07-25 16:27:50 -1000 my user timezone is Hawaii at -10 from UTC, but this only shows a 6 hr difference?

2 - How do I get this in a format that is easily readable by users (07/25/2013 12:27 PM)? Thanks again

Solved: Thanks to Benjamin. I forgot to mention that I'm (stuck) using 1.8.7, so I had to work through a few minor differences between 1.8.7 and 1.9.3, but got it working with:

<%= DateTime.strptime(item[1], '%Y-%m-%d %H:%M:%S').in_time_zone(Time.zone).to_formatted_s(:long)%>

Updated: Got it into the format I wanted (06/20/2013 01:00 AM) using:

DateTime.strptime(item[1], '%Y-%m-%d %H:%M ').in_time_zone(Time.zone).strftime("%m/%d/%Y %I:%M %p") 

Upvotes: 1

Views: 4881

Answers (1)

Benjamin Bouchet
Benjamin Bouchet

Reputation: 13181

Try this

Time.strptime(item[1], '%Y-%m-%dT%H:%M:%S%z').in_time_zone(Time.zone) 

Answer to the bonus questions

  1. Check the time zone of your db server and double check your rails data (default config / user TZ)

  2. use to_formatted_s http://api.rubyonrails.org/classes/Time.html#method-i-to_formatted_s

Upvotes: 1

Related Questions