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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With