DateTime.now or Time.now? DateTime.now or Time.now? ruby ruby

DateTime.now or Time.now?


Use (Date)Time.current instead of (Date)Time.now

Rails extends the Time and DateTime objects, and includes the current property for retrieving the time the Rails environment is set to (default = UTC), as opposed to the server time (Could be anything).

This is critical- You should always be working in UTC time except when converting between timezones for user input or display- but many production systems are not UTC by default. (e.g. Heroku is set to PST (GMT -8))

See article here


In reference to Time.now (not DateTime.now):

The object created will be created using the resolution available on your system clock, and so may include fractional seconds.

a = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003b = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003a == b            #=> false"%.6f" % a.to_f   #=> "1049896563.230740""%.6f" % b.to_f   #=> "1049896563.231466"


If you want to get the time in the application's time zone, you'll need to call Time.zone.now, so that's what I generally use.

Time.now and DateTime.now will both return a time in the system's time, which often is set to UTC.