mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Get UTC Offset For Different Time Zones as a Ruby TIL
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||
|
||||
_1408 TILs and counting..._
|
||||
_1409 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -1137,6 +1137,7 @@ _1408 TILs and counting..._
|
||||
- [Generate Ruby Version And Gemset Files With RVM](ruby/generate-ruby-version-and-gemset-files-with-rvm.md)
|
||||
- [Get Info About Your RubyGems Environment](ruby/get-info-about-your-ruby-gems-environment.md)
|
||||
- [Get The Output Of Running A System Program](ruby/get-the-output-of-running-a-system-program.md)
|
||||
- [Get UTC Offset For Different Time Zones](ruby/get-utc-offset-for-different-time-zones.md)
|
||||
- [Identify Outdated Gems](ruby/identify-outdated-gems.md)
|
||||
- [If You Detect None](ruby/if-you-detect-none.md)
|
||||
- [Iterate With An Offset Index](ruby/iterate-with-an-offset-index.md)
|
||||
|
||||
42
ruby/get-utc-offset-for-different-time-zones.md
Normal file
42
ruby/get-utc-offset-for-different-time-zones.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# Get UTC Offset For Different Time Zones
|
||||
|
||||
The [IANA Time Zone Database](https://www.iana.org/time-zones) uses identifiers
|
||||
like `America/Chicago`, `Asia/Hong_Kong`, `Africa/Nairobi`, etc. as specifiers
|
||||
for notable locations with time zone information.
|
||||
|
||||
> Most timezones correspond to a notable location and the database records all
|
||||
> known clock transitions for that location; some timezones correspond instead
|
||||
> to a fixed UTC offset.
|
||||
—[Theory and pragmatics of the tz code and data](https://data.iana.org/time-zones/theory.html)
|
||||
|
||||
These identifiers can be used to look up time zone details with the [`tzinfo`
|
||||
gem](https://github.com/tzinfo/tzinfo).
|
||||
|
||||
Here is an example of passing one to the `#get` method and then getting the UTC
|
||||
offset in seconds.
|
||||
|
||||
```ruby
|
||||
> require 'tzinfo'
|
||||
|
||||
> mountain = TZInfo::Timezone.get('America/Denver')
|
||||
=> #<TZInfo::DataTimezone: America/Denver>
|
||||
> mountain.utc_offset
|
||||
=> -21600
|
||||
```
|
||||
|
||||
We can even get the base UTC offset that doesn't account for DST:
|
||||
|
||||
```ruby
|
||||
> moutain.base_utc_offset
|
||||
=> -25200
|
||||
```
|
||||
|
||||
Notice, this is the same as the standard offset for a time zone like Phoenix
|
||||
that doesn't observe DST.
|
||||
|
||||
```ruby
|
||||
> phoenix = TZInfo::Timezone.get('America/Phoenix')
|
||||
=> #<TZInfo::DataTimezone: America/Phoenix>
|
||||
> phoenix.utc_offset
|
||||
=> -25200
|
||||
```
|
||||
Reference in New Issue
Block a user