Kartikey Tanna
Kartikey Tanna

Reputation: 1459

The number in date format while using Rails and Postgres

I have a Rails app which uses Postgresql.

Please check out the following command and its output from Rails console:

[11] pry(main)> User.last.created_at_before_type_cast
  User Load (0.6ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT $1  [["LIMIT", 1]]
=> "2018-08-29 11:10:46.526069"

What does the number 526069 represent and how it gets generated?

Upvotes: 0

Views: 1621

Answers (2)

The Wizard
The Wizard

Reputation: 953

Postgres stores timestamps with timezones internally using UTC, however before displaying ActiveRecord will serialize/typecast to your application's timezone.

pry(main)>d = DateTime.now.in_time_zone("Asia/Kolkata") => Sat, 07 Oct 2017 00:38:26 IST +05:30 pry(main)> Booking.where('created_at > ?', d).count (1.4ms) SELECT COUNT(*) FROM "bookings" WHERE (created_at > '2017-10-06 19:08:40.011480')

As you can see, d was converted to UTC to perform the search in the postgres database.
The created_at_before_type_cast method will return the value of created_at exactly how it's stored in the database without serializing/typecasting based on your ActiveRecord configuration.

As bkimble already pointed out: The numbers at the end are milliseconds.

You should have a look at the following for a deeper understanding:

Upvotes: 4

Billy Kimble
Billy Kimble

Reputation: 820

That represents microseconds. See https://ruby-doc.org/core-2.2.2/Time.html . By default, all Time has microseconds. Check it out yourself by casting Time.now to float:

Time.now.to_f
= > 1535595572.4089978

If you want to drop the microseconds, cast it to int:

Time.now.to_i
=> 1535595649

I'd imagine a field like 'created_at_before_type_cast' represents the Time before it gets cast to an integer.

Upvotes: 2

Related Questions