123
123

Reputation: 8951

Get UTC offset of time string without string manipulation

I have a time string that looks like this: time = "7:00 PM -0500"

The offset of this is clearly -0500, and I can get that by doing utc_offset = time[-5..-1]

However, I want to do this with the existing Ruby Time functionality, instead of using string manipulation.

This needs to work for all time zones, so I can't hardcode a timezone or offset anywhere. How can I take a string in the format "<hour>:<minutes> <am/pm> <offset>", parse it, and get the correct offset just using functionality in the Time class?

Upvotes: 0

Views: 68

Answers (1)

Oleksandr Holubenko
Oleksandr Holubenko

Reputation: 4440

Maybe, this should help you next time, for this your question possible answer is:

require 'time'
time = "7:00 PM -0500"
Time.parse(time).strftime "%z"
 => "-0500" 

UPD

If Time.parse return just your local timezone(in some ruby-versions), you can also try this:

require 'time'
time = "7:00 PM -0500"
DateTime.parse(time).strftime "%z"
=> "-0500" 

Upvotes: 1

Related Questions