Skip to content

Commit 476a043

Browse files
committed
Add Change The Time Zone Offset Of A DateTime Object as a rails til
1 parent c0ffd2f commit 476a043

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1060 TILs and counting..._
13+
_1061 TILs and counting..._
1414

1515
---
1616

@@ -638,6 +638,7 @@ _1060 TILs and counting..._
638638
- [Capybara Page Status Code](rails/capybara-page-status-code.md)
639639
- [Cast Common Boolean-Like Values To Booleans](rails/cast-common-boolean-like-values-to-booleans.md)
640640
- [Change The Nullability Of A Column](rails/change-the-nullability-of-a-column.md)
641+
- [Change The Time Zone Offset Of A DateTime Object](rails/change-the-time-zone-offset-of-a-datetime-object.md)
641642
- [Check If ActiveRecord Update Fails](rails/check-if-activerecord-update-fails.md)
642643
- [Check Specific Attributes On ActiveRecord Array](rails/check-specific-attributes-on-activerecord-array.md)
643644
- [Code Statistics For An Application](rails/code-statistics-for-an-application.md)
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Change The Time Zone Offset Of A DateTime Object
2+
3+
Let's say you have a timestamp string that you parse with
4+
[`DateTime.parse`](https://ruby-doc.org/stdlib-2.6.1/libdoc/date/rdoc/DateTime.html#method-c-parse).
5+
6+
```ruby
7+
> DateTime.parse('2021-02-23T11:59:11')
8+
#=> Tue, 23 Feb 2021 11:59:11 +0000
9+
```
10+
11+
Without the specification of a time zone offset in the timestamp string, it
12+
will be parsed as UTC.
13+
14+
If you want to change it to another time zone, you can alter the `offset`
15+
option of the `DateTime` object. Rails provides the
16+
[`#change`](https://api.rubyonrails.org/classes/DateTime.html#method-i-change)
17+
method for doing this.
18+
19+
```ruby
20+
> DateTime.parse('2021-02-23T11:59:11').change(offset: '-600')
21+
#=> Tue, 23 Feb 2021 11:59:11 -0600
22+
```
23+
24+
By changing the `offset` to `-600`, the `DateTime` now represents a time in
25+
Central Time.
26+
27+
[source](https://stackoverflow.com/a/47861810/535590)

0 commit comments

Comments
 (0)