From f9ae92948b948825428676753cae88735ca129d1 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 28 Jan 2021 20:36:36 -0600 Subject: [PATCH] Add Get The Current Time as a rails til --- README.md | 3 ++- rails/get-the-current-time.md | 38 +++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 rails/get-the-current-time.md diff --git a/README.md b/README.md index bd8dd4c..6ae989a 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://tinyletter.com/jbranchaud). -_1029 TILs and counting..._ +_1030 TILs and counting..._ --- @@ -641,6 +641,7 @@ _1029 TILs and counting..._ - [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 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) - [Hash Slicing](rails/hash-slicing.md) - [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md) - [Include Devise Helpers In Your Controller Tests](rails/include-devise-helpers-in-your-controller-tests.md) diff --git a/rails/get-the-current-time.md b/rails/get-the-current-time.md new file mode 100644 index 0000000..8af24d4 --- /dev/null +++ b/rails/get-the-current-time.md @@ -0,0 +1,38 @@ +# Get The Current Time + +Working with time and time zones in server development can get complicated. +Time-sensitive code that worked locally can unexpected fail when deployed to a +server in a different time zone. Or users can end up seeing timestamps that +look a few hours off. + +To avoid this kinds of mistakes in Rails development, we should avoid using +`Time.now` and instead use `Time.current`. + +> Rails saves timestamps to the database in UTC time zone. We should always use +> Time.current for any database queries, so that Rails will translate and +> compare the correct times. + +```ruby +> Time.zone +=> #, + @utc_offset=nil> +> Time.now +=> 2021-01-28 19:22:42.312577 -0600 +> Time.current +=> Fri, 29 Jan 2021 01:22:45.926181000 UTC +00:00 +> Time.zone = 'Eastern Time (US & Canada)' +=> "Eastern Time (US & Canada)" +> Time.now +=> 2021-01-28 19:23:28.255106 -0600 +> Time.current +=> Thu, 28 Jan 2021 20:23:32.150545000 EST -05:00 +``` + +My server's default time zone is UTC. `Time.now` gives me my computer's system +time (Central Time). `Time.current` gives me the time in UTC. If I then change +the server's time zone to Eastern Time, `Time.now` still offers up my system +time whereas `Time.current` produces the current time in Easter Time. + +[source](https://thoughtbot.com/blog/its-about-time-zones)