123
123

Reputation: 8951

Take separate time and timezone strings, and convert into UTC

I know a bunch of ways to convert local times into UTC time with Ruby, but I'm not sure how to do this when the time and the zone are separate pieces of data. If I have something like "12:00 PM -0500", I can easily convert this into UTC with .getutc(). However, what if I have "12:00 PM" and "Eastern Time (US & Canada)"? How can I combine these two to find the UTC time?

Upvotes: 1

Views: 45

Answers (2)

Kevin Leahey
Kevin Leahey

Reputation: 31

The DateTime::parse method may be what you are looking for.

x = DateTime.parse("12:00 PM Eastern Time (US & Canada)")

will return a result of

#<DateTime: 2017-11-15T12:00:00-05:00 ((2458073j,61200s,0n),-18000s,2299161j)> 

From there, there are many ways to convert the time to UTC. For example,

utc = x.new_offset(0)

will return a result of

#<DateTime: 2017-11-15T17:00:00+00:00 ((2458073j,61200s,0n),+0s,2299161j)>

Upvotes: 3

moveson
moveson

Reputation: 5213

If you are using Rails, or if you don't mind requiring ActiveSupport, you can use ActiveSupport::TimeZone to do this.

>> time_zone = "Eastern Time (US & Canada)"
>> time_without_zone = "12:00 PM"
>> ActiveSupport::TimeZone[time_zone].parse(time_without_zone)
#=> Wed, 15 Nov 2017 12:00:00 EST -05:00

Upvotes: 0

Related Questions