Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got code that does time tracking for employees. It creates a counter to show the employee how long they have been clocked in for.

This is the current code:

  start_time = Time.parse(self.settings.first_clock_in)   total_seconds = Time.now - start_time   hours = (total_seconds/ 3600).to_i   minutes = ((total_seconds % 3600) / 60).to_i   seconds = ((total_seconds % 3600) % 60).to_i 

This works fine. But because Time is limited to the range of 1970 - 2038 we are trying to replace all Time uses with DateTimes. I can't figure out how to get the number of seconds between two DateTimes. Subtracting them yields a Rational which I don't know how to interpret, whereas subtracting Times yields the difference in seconds.

NOTE: Since Ruby 1.9.2, the hard limit of Time is removed. However, Time is optimized for values between 1823-11-12 and 2116-02-20.

like image 438
Tilendor Avatar asked Feb 19 '09 22:02

Tilendor


People also ask

How do you tell the time difference in Ruby?

Because when hours_elapsed '2015-12-31 22:00:00 +0100', '2015-12-31 02:00:00 +0100' would give 4 hours_elapsed '2015-12-21 22:00:00 +0100', '2015-12-31 02:00:00 +0100' would give 220.0 and I'm only need the hours and min.


2 Answers

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 
like image 60
David Ma Avatar answered Sep 30 '22 03:09

David Ma


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] 
like image 42
Avram Dorfman Avatar answered Sep 30 '22 01:09

Avram Dorfman