aRtoo
aRtoo

Reputation: 1892

When retrieving time stamp in rails, it is being converted or rounded down. How do I prevent this?

I have a completed_at column on my database with the values 2021-03-05 00:17:31.059123, and 2021-03-05 00:08:00.257058 but when I retrieve this it's showing/displaying Thu, 04 Mar 2021 16:17:31 PST -08:00, and Thu, 04 Mar 2021 16:08:00 PST -08:00 respectively.

How is it on my database it's displaying March 5, 2021 but when I retrieve the data it's March 4, 2021. Is there a way to prevent this?

Ruby version: 2.3.6

Rails version: 4.2.6

Postgres version: 9.6

Upvotes: 0

Views: 40

Answers (1)

Paulo Abreu
Paulo Abreu

Reputation: 1786

That happens because Rails uses your app timezone (see Time.zone) but when the date is stored in the database, is stored in UTC. As such, if you inspect the timestamp on your database, for instance, using a GUI to inspect a table and its rows, you will see that date in UTC.

Try to set your app time zone to something else. Open the rails console, and play with it:

irb(main):001:0> Time.zone
=> #<ActiveSupport::TimeZone:0x00007ff13688d180 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::DataTimezone: Etc/UTC>>

irb(main):002:0> User.last.created_at
  User Load (2.7ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT $1  [["LIMIT", 1]]
=> Tue, 26 Jan 2021 13:47:58.769517000 UTC +00:00

irb(main):003:0> Time.zone = "Alaska"
=> "Alaska"

irb(main):004:0> User.last.created_at
  User Load (0.4ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT $1  [["LIMIT", 1]]
=> Tue, 26 Jan 2021 04:47:58.769517000 AKST -09:00

irb(main):006:0> User.last.created_at.utc
  User Load (0.3ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT $1  [["LIMIT", 1]]
=> 2021-01-26 13:47:58.769517 UTC

Some reading recommendations:

The Exhaustive Guide to Rails Time Zones and WORKING WITH TIME ZONES IN RUBY ON RAILS.

You can also see the documentation for TimeWithZone, Time and TimeZone.

Upvotes: 2

Related Questions