Reputation: 3912
In my rails4 app, I have date given in two strings, one gives timestamp, while other gives which timezone this is in:
a = "04/23/2014 04:00"
b = "Eastern Time (US & Canada)"
I want to convert this date to utc, so that I can save it in UTC
"2014-04-23 08:00:00 UTC"
What is the best way to do it?
Upvotes: 0
Views: 1150
Reputation: 26193
Using the strptime
method on the Rails DateTime
class, you can parse a DateTime
object from a string containing both the time and timezone (timezone is passed via the %z
directive). From there, you can convert the time to UTC:
a = "04/23/2014 04:00"
b = "Eastern Time (US & Canada)"
datetime_with_tz = DateTime.strptime([a, b].join(' '), "%m/%d/%Y %H:%M %z")
#=> Wed, 23 Apr 2014 04:00:00 -0500
datetime_with_tz.utc
#=> Wed, 23 Apr 2014 09:00:00 +0000
Upvotes: 1
Reputation: 2786
Use the in_time_zone method of the DateTime class
Loading development environment (Rails 2.3.2)
>> now = DateTime.now.utc
=> Sun, 06 Sep 2009 22:27:45 +0000
>> now.in_time_zone('Eastern Time (US & Canada)')
=> Sun, 06 Sep 2009 18:27:45 EDT -04:00
>> quit
So for your particular example
a.in_time_zone('Eastern Time (US & Canada)')
Upvotes: 0