Just Another Tech Journal

Projects

Elsewhere

Time.now vs Time.zone.now

Ruby Time can get confusing when used in your Rails app. What Time is it now?

Suppose I have a server in UTC time and all of my users are from Singapore (GMT +08:00),
then your Rails app's time_zone should be configured to SGT.

# config/application.rb# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.config.time_zone='Singapore'

Besides that, instead of using Time.now, use Time.zone.now especially when
you are printing time attributes as display to your users.

Now then.. What do you do when you query the database with ActiveRecord?

You can use either Time.now or Time.current.
Both will work because ActiveRecord will convert the times to UTC before sending it to the database,
as all time columns in the database are also stored in UTC. Let's verify..