Created
April 29, 2015 23:59
-
-
Save mmasashi/29027a67edcb19f84c95 to your computer and use it in GitHub Desktop.
How to chnage the timezone of ruby Time object
This file contains hidden or 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
| require 'tzinfo' | |
| require 'date' | |
| TIMEZONES = { | |
| 'us-east-1' => 'US/Eastern', | |
| 'us-west-1' => 'US/Pacific', | |
| 'us-west-2' => 'US/Pacific', | |
| 'eu-west-1' => 'GB', | |
| 'ap-southeast-1' => 'Singapore', | |
| 'ap-northeast-1' => 'Japan', | |
| 'sa-east-1' => 'Sao_Paulo', | |
| } | |
| def time_at_tz(time, tz_or_region) | |
| timezone = if TIMEZONES[tz_or_region] | |
| TIMEZONES[tz_or_region] | |
| else | |
| tz_or_region | |
| end | |
| tz = TZInfo::Timezone.get(timezone) | |
| value = case time | |
| when Integer | |
| Time.at(time).utc | |
| when Time | |
| time.utc | |
| else | |
| raise ArgumentError.new("Invalid time. #{time}") | |
| end | |
| local_time = tz.utc_to_local value | |
| end | |
| # test | |
| value = 1429066136 | |
| puts Time.at value | |
| puts (Time.at value).utc | |
| puts time_at_tz(value, 'US/Eastern') | |
| puts time_at_tz(value, 'ap-northeast-1') |
This file contains hidden or 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
| 2015-04-14 19:48:56 -0700 | |
| 2015-04-15 02:48:56 UTC | |
| 2015-04-14 22:48:56 UTC | |
| 2015-04-15 11:48:56 UTC |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since the Ruby Time class supports two timezones(utc and local), timezone of returned time object has always UTC timezone.
https://github.com/tzinfo/tzinfo