Reputation: 65497
Which of the two should I be using in my Rails application:
DateTime.now or Time.now
Is there any harm in using both in the application?
Can there ever be any differences between the two in case of the above (now
) example? (On my current system they are both showing the same time)
Upvotes: 45
Views: 45066
Reputation: 183679
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
Upvotes: 59
Reputation: 1152
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.
Upvotes: 8
Reputation: 24052
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 2003
b = Time.new #=> Wed Apr 09 08:56:03 CDT 2003
a == b #=> false
"%.6f" % a.to_f #=> "1049896563.230740"
"%.6f" % b.to_f #=> "1049896563.231466"
Upvotes: 18