diff --git a/README.md b/README.md index 1261011..d23d68c 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/rails/get-formatted-utc-offset-value.md b/rails/get-formatted-utc-offset-value.md new file mode 100644 index 0000000..5f846e4 --- /dev/null +++ b/rails/get-formatted-utc-offset-value.md @@ -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') +=> # +> ActiveSupport::TimeZone.seconds_to_utc_offset(chicago.utc_offset) +=> "-05:00" + +> newfoundland = TZInfo::Timezone.get('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') +=> # +> ActiveSupport::TimeZone[chicago.name] +=> #, @utc_offset=nil> +> ActiveSupport::TimeZone[chicago.name].formatted_offset +=> "-06:00" +> ActiveSupport::TimeZone[chicago.name].formatted_offset(false) +=> "-0600" +```