How to use ‘Time’ in Rails projects?
You shouldn’t be confused while you use the Ruby ‘Time’ within your Rails project.
You should be aware of if your project uses the desired time zone or it simply takes your current system local time zone.
If you have configured the time zone within your rails application, always use the current
for Time
or DateTime
object.
If you haven’t set any timezone you could use the now
for the Time
or DateTime
object, but I still recommend usages of current
Why you should use Time.current
or DateTime.current
?
If you choose the .current
for the Time
or DateTime
it will make the decision whether to show time in timezone or local. It simply makes the decision based on timezone setting If it set to use it otherwise use local time.
here is the source snippet
# rails/activesupport/lib/active_support/core_ext/date_time/calculations.rb
class DateTime
class << self
def current
::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
end
end
end
# rails/activesupport/lib/active_support/core_ext/time/calculations.rb
class Time
class << self
def current
::Time.zone ? ::Time.zone.now : ::Time.now
end
end
end
you can view the source code in GitHub for .current
, It makes this stuff very clear