neezer
neezer

Reputation: 20560

Ruby: Math functions for Time Values

How do I add/subtract/etc. time values in Ruby? For example, how would I add the following times?

00:00:59 + 00:01:43 + 00:20:15 = ?

Upvotes: 3

Views: 4473

Answers (4)

Arman H
Arman H

Reputation: 5618

Use ActiveSupport, which has a ton of built-in date extensions.

require 'active_support/core_ext'
t1 = "#{Date.today} 00:00:59".to_time
t2 = "#{Date.today} 00:01:43".to_time
t3 = "#{Date.today} 00:20:15".to_time
t1.since(t2.seconds_since_midnight+t3.seconds_since_midnight)

or, if you don't care about the date, only time:

t1.since(t2.seconds_since_midnight+t3.seconds_since_midnight).strftime("%H:%M:%S")

For a full list, check out http://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-date

Upvotes: 1

fooyay
fooyay

Reputation: 96

You probably want to use a gem that does not concern itself with the actual day. You could perform acrobatics using DateTime and or Time, but you would constantly be battling how to handle days.

One gem that may be useful is tod (TimeOfDay), https://github.com/JackC/tod

With that you could directly do TimeOfDay.parse "00:01:43", add the values, and print the result using strftime("%H:%M:%S").

Upvotes: 0

chopi321
chopi321

Reputation: 1411

One way would be to convert everything to seconds and then performing the operations... Then you would need to convert it again to a time object with

Time.at(seconds_result).strftime('%H:%M:%S')

And you would get the time nicely formatted (as a string).

I am trying to find a gem that does this, and other operations.

Upvotes: 0

David
David

Reputation: 1143

Kind of ugly, but you could use DateTime.parse(each_interval) & calculate the number of seconds in each. Like this:

require 'date'

def calc_seconds(time_string)
  date_time = DateTime.parse(time_string)
  hour_part = date_time.hour * 60 * 60
  minute_part = date_time.minute * 60
  second_part = date_time.second
  hour_part + minute_part + second_part
end

...which gives you your result in seconds, assuming valid inputs. At which point you can add them together.

You could reverse the process to get the interval in your original notation.

I really think there ought to be an easier method, but I don't know of one.

Upvotes: 0

Related Questions