Created
January 23, 2014 16:15
-
-
Save cpuguy83/8581441 to your computer and use it in GitHub Desktop.
Time zone parsing from local time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OperatingHour | |
class MissingTimeZoneError < StandardError; end | |
class MissingTimeStringError < StandardError; end | |
attr_reader :time_string, :time_zone | |
def initialize(opts={}) | |
@time_string = opts[:time_string] | |
@time_zone = opts[:time_zone] | |
end | |
def to_utc_time | |
raise MissingTimeStringError unless @time_string | |
raise MissingTimeZoneError unless @time_zone | |
store_normal_time_zone | |
set_time_zone | |
time = parse_time_string | |
time.utc | |
ensure | |
cleanup_time_zone | |
end | |
private | |
def parse_time_string | |
Time.zone.parse(@time_string) | |
end | |
def store_normal_time_zone | |
@normal_time_zone = Time.zone.name | |
end | |
def set_time_zone | |
Time.zone = time_zone | |
end | |
def cleanup_time_zone | |
Time.zone = @normal_time_zone if @normal_time_zone | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment