How do I get the number of seconds between two DateTimes in Ruby on Rails

Subtracting two DateTimes returns the elapsed time in days, so you could just do:

elapsed_seconds = ((end_time - start_time) * 24 * 60 * 60).to_i

Or, more readably:

diff = datetime_1 - datetime_2
diff * 1.days # => difference in seconds; requires Ruby on Rails

Note, what you or some other searchers might really be looking for is this:

diff = datetime_1 - datetime_2
Date.day_fraction_to_time(diff) # => [h, m, s, frac_s]

You can convert them to floats with to_f, though this will incur the usual loss of precision associated with floats. If you're just casting to an integer for whole seconds it shouldn't be big enough to be a worry.

The results are in seconds:

>> end_time.to_f - start_time.to_f
=> 7.39954495429993

>> (end_time.to_f - start_time.to_f).to_i
=> 7

Otherwise, you could look at using to_formatted_s on the DateTime object and seeing if you can coax the output into something the Decimal class will accept, or just formatting it as plain Unix time as a string and calling to_i on that.


Others incorrectly rely on fractions or helper functions. It's much simpler than that. DateTime itself is integer underneath. Here's the Ruby way:

stop.to_i - start.to_i

Example:

start = Time.now
 => 2016-06-21 14:55:36 -0700
stop = start + 5.seconds
 => 2016-06-21 14:55:41 -0700
stop.to_i - start.to_i
 => 5