Convert time to time zone : Time Zones « Time « Ruby






Convert time to time zone


class Time
  def convert_zone(to_zone)
    original_zone = ENV["TZ"]
    utc_time = dup.gmtime
    ENV["TZ"] = to_zone
    to_zone_time = utc_time.localtime
    ENV["TZ"] = original_zone
    return to_zone_time
  end
end
convert_zone("US/Pacific")

t = Time.at(1000000000)                # => Sat Sep 08 21:46:40 EDT 2001

t.convert_zone("US/Pacific")           # => Sat Sep 08 18:46:40 PDT 2001

convert_zone("US/Alaska")

t = Time.at(1000000000)                # => Sat Sep 08 21:46:40 EDT 2001

t.convert_zone("US/Alaska")            # => Sat Sep 08 17:46:40 AKDT 2001

convert_zone("UTC")

t = Time.at(1000000000)                # => Sat Sep 08 21:46:40 EDT 2001

t.convert_zone("UTC")                  # => Sun Sep 09 01:46:40 UTC 2001

convert_zone("Turkey")

t = Time.at(1000000000)                # => Sat Sep 08 21:46:40 EDT 2001

t.convert_zone("Turkey")               # => Sun Sep 09 04:46:40 EEST 2001

convert_zone("Asia/Calcutta")

t = Time.at(1000000000)                # => Sat Sep 08 21:46:40 EDT 2001

t.convert_zone("Asia/Calcutta")        # => Sun Sep 09 07:16:40 IST 2001

ENV["TZ"] = "Africa/Lagos"

ENV["TZ"] = "Africa/Lagos"
t = Time.at(1000000000)                # => Sun Sep 09 02:46:40 WAT 2001
ENV["TZ"] = nil

puts t.convert_zone("Singapore")            # => Sun Sep 09 09:46:40 SGT 2001

puts t.convert_zone("US/Eastern")           # => Sat Sep 08 21:46:40 EDT 2001

 








Related examples in the same category

1.Converting Between Time Zones