Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should `DateTime.now.utc` vs. `Time.current.utc` be used in Rails?

Tags:

In Rails, I'm a little confused on the guidance between when to use DateTime.now.utc and Time.current. There seem to be differing opinions inside the framework about which is best, particularly in different versions.

It looks like DateTime.now.utc produces a timestamp with a UTC offset of zero, while Time.current.utc produces a timestamp with a time zone of UTC. That seems like a subtle distinction but it's pretty important in many cases (e.g. DST calculations).

When should you use DateTime.now.utc, and when should you use Time.current.utc? Is there any reason to use DateTime.now.utc instead of Time.current.utc?

like image 446
John Feminella Avatar asked Oct 05 '12 14:10

John Feminella


People also ask

Does DateTime use UTC?

The property UtcNow of the DateTime class returns the current date and time of the machine running the code, expressed in UTC format. UTC is a universal format to represent date and time as an alternative to local time. Also known as the GMT+00 timezone.

What does DateTime now return in Ruby?

DateTime#now() : now() is a DateTime class method which returns a DateTime object denoting the given calendar date. Return: DateTime object denoting the given calendar date.

What is time now Ruby?

The now() is an inbuilt method in Ruby returns the current time. Syntax: time.now() Parameters: The function accepts no parameter. Return Value: It returns the current time.

How do you parse time in Ruby?

parse takes a string representation of a Time and attempts to parse it using a heuristic. Any missing pieces of the date are inferred based on the current date. We can change the date used to infer our missing elements by passing a second object that responds to mon, day and year, such as Date, Time or DateTime.


1 Answers

I think you should use .current instead of .now.

The difference of .current and .now is .now use the server's timezone, while .current use what the Rails environment is set to. If it's not set, then .current will be same as .now.

Time.current

Returns Time.zone.now when Time.zone or config.time_zone are set, otherwise just returns Time.now.

DateTime.current

Returns Time.zone.now.to_datetime when Time.zone or config.time_zone are set, otherwise returns Time.now.to_datetime.

like image 199
xdazz Avatar answered Sep 20 '22 12:09

xdazz