Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to parse date-time string into a specific time zone

I'm using Rails 3.2 and ruby 1.9.3 on Debian. I have an app that collects a date, time, and timezone in the form of strings via an HTML form. Something like this:

start_date: "04-15-2010", start_time: "10:00:00", timezone: "Central Time (US & Canada)" 

What I'd like to do is parse these 3 elements into a single date that is saved into my database as UTC, which in this case would add 7 hours to the start time, once it's in the UTC time zone. So the stored time would be 17:00 once it's in the DB as UTC instead of the received Central time.

I have tried something like this to parse the date:

ActiveSupport::TimeZone[timezone].at DateTime.strptime("{ 2012-04-09 20:00:00 }", "{ %Y-%m-%d %H:%M:%S }").to_i 

However, I'm not able to incorporate the time zone into the resulting time with %Z. It either doesn't parse or the time is interpreted as UTC not Central time. So my question is, how to coerce a date string into a certain time zone without changing the value of the actual date/time stored. I'd like to be able to parse the string into a date/time object that includes the correct time zone with it at that time so that future time zone conversions are accurate. I've looked all over and can't find a way to do this. It's strange, since this seems like something common one does with dates inputted from HTML forms. Thank you for any help.

like image 817
Matt Schwartz Avatar asked Apr 10 '12 15:04

Matt Schwartz


People also ask

How do you parse time in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.

How do you parse time from a date?

The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.


2 Answers

Try this:

zone = "Central Time (US & Canada)"    ActiveSupport::TimeZone[zone].parse("2013-04-03 17:47:00") 
like image 72
ryancheung Avatar answered Oct 26 '22 22:10

ryancheung


Use String#in_time_zone (Rails 4+)

I personally prefer using String#in_time_zone:

>> '22.09.1986 10:30'.in_time_zone('Central Time (US & Canada)') # => Mon, 22 Sep 1986 10:30:00 CDT -05:00 

This parses the date and time in the String into the time zone provided.

like image 31
Artur Beljajev Avatar answered Oct 26 '22 22:10

Artur Beljajev