mirror of
https://github.com/jbranchaud/til
synced 2026-01-05 16:18:01 +00:00
Add Get Formatted UTC Offset Value as a Rails 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).
|
||||
|
||||
_1409 TILs and counting..._
|
||||
_1410 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -879,6 +879,7 @@ _1409 TILs and counting..._
|
||||
- [Get ActiveRecord Attribute Directly From Database](rails/get-active-record-attribute-directly-from-database.md)
|
||||
- [Get An Array Of Values From The Database](rails/get-an-array-of-values-from-the-database.md)
|
||||
- [Get An Empty ActiveRecord Relation](rails/get-an-empty-activerecord-relation.md)
|
||||
- [Get Formatted UTC Offset Value](rails/get-formatted-utc-offset-value.md)
|
||||
- [Get Help With A Rails App Update](rails/get-help-with-a-rails-app-update.md)
|
||||
- [Get The Column Names For A Model](rails/get-the-column-names-for-a-model.md)
|
||||
- [Get The Current Time](rails/get-the-current-time.md)
|
||||
|
||||
37
rails/get-formatted-utc-offset-value.md
Normal file
37
rails/get-formatted-utc-offset-value.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# Get Formatted UTC Offset Value
|
||||
|
||||
The UTC offset (during DST) for Chicago is `-05:00`. And for Newfoundland it is
|
||||
`-02:30`.
|
||||
|
||||
Rails has an [`ActiveSupport::TimeZone`
|
||||
module](https://api.rubyonrails.org/v7.1.3.2/classes/ActiveSupport/TimeZone.html#method-c-seconds_to_utc_offset)
|
||||
that can turn the UTC offset in seconds into this formatted value.
|
||||
|
||||
```ruby
|
||||
> chicago = TZInfo::Timezone.get('America/Chicago')
|
||||
=> #<TZInfo::DataTimezone: America/Chicago>
|
||||
> ActiveSupport::TimeZone.seconds_to_utc_offset(chicago.utc_offset)
|
||||
=> "-05:00"
|
||||
|
||||
> newfoundland = TZInfo::Timezone.get('America/St_Johns')
|
||||
=> #<TZInfo::DataTimezone: America/St_Johns>
|
||||
> ActiveSupport::TimeZone.seconds_to_utc_offset(newfoundland.utc_offset)
|
||||
=> "-02:30"
|
||||
```
|
||||
|
||||
The underlying `tzinfo` gem is DST-aware and its database even knows which time
|
||||
zone identifiers don't observe DST, so you can run this anytime of the year and
|
||||
expect reliable results.
|
||||
|
||||
Here is another way at this:
|
||||
|
||||
```ruby
|
||||
> chicago = TZInfo::Timezone.get('America/Chicago')
|
||||
=> #<TZInfo::DataTimezone: America/Chicago>
|
||||
> ActiveSupport::TimeZone[chicago.name]
|
||||
=> #<ActiveSupport::TimeZone:0x00000001099d8140 @name="America/Chicago", @tzinfo=#<TZInfo::DataTimezone: America/Chicago>, @utc_offset=nil>
|
||||
> ActiveSupport::TimeZone[chicago.name].formatted_offset
|
||||
=> "-06:00"
|
||||
> ActiveSupport::TimeZone[chicago.name].formatted_offset(false)
|
||||
=> "-0600"
|
||||
```
|
||||
Reference in New Issue
Block a user