Thursday, June 5, 2008

Timezone conversion in Ruby

The time in the feed is supplied with 2 fields - date and time. It is in UTC. The date looks like 20080605, and the time looks like 142115. I need to display the current local date and time. I could've used a regular expression to parse the date/time into components, but I wanted to use strptime. The Time module does not have strptime, but the DateTime module does. Once parsed, the DateTime object is in UTC. To get local time, use the new_offset method.
require "Date"

# time_str will look like "20080605 142115 UTC".
time_str = feed_date + " " + feed_time + " UTC"

# Parse time_str into a DateTime object.
dt = DateTime.strptime(time_str, "%Y%m%d %H%M%S %Z")

# local_dt will contain the date and time in the local timezone.
local_dt = dt.new_offset(

display_dt_str = local_dt.strftime("%Y-%m-%d %H:%M")