Anil Pediredla
Anil Pediredla

Reputation: 744

Time operations in ruby

I am new to ruby. I am trying to calculate the number of seconds for a given period. I have a start time and end time with HH:MM:SS format.

Can I declare a variable as object of Time class and perform calculations? Example:

start_time='15:00:12'
end_time='19:32:12'
a=Time.new(start_time)
b=Time.new(end_time)
duration_seconds=a-b

Upvotes: 1

Views: 383

Answers (4)

Manish Kongari
Manish Kongari

Reputation: 161

Try this

end_time=Time.strptime('19:32:12',"%H:%M:%S")
start_time=Time.strptime('15:00:12',"%H:%M:%S")
end_time-start_time

Upvotes: 0

Horacio
Horacio

Reputation: 2965

You can try doing

require "time"
start_time='15:00:12'
end_time='19:32:12'
Time.new(2002,1,1,*end_time.split(":")) - Time.new(2002,1,1,*start_time.split(":"))

I assume that you want to know time in the same day. And I put the END - START to get positive values.

Upvotes: 1

Wand Maker
Wand Maker

Reputation: 18762

Here is the code in Ruby

Since Time.new expects parameters like year, month, day, hour, minute, seconds - I have used current time for first 3 parameter, and the values from the string parameter that OP had for rest of 3 parameters

Getting difference between the two time - I have used to_i method which returns number of seconds from Epoch that Time instance represents

string_start_time ='15:00:12'
start_time_parts = string_start_time.split(":").collect{ |y| y.to_i }
start_time = Time.new(Time.now.year, Time.now.month, Time.now.day, start_time_parts[0], start_time_parts[1], start_time_parts[2])
p start_time

string_end_time='19:32:12'
end_time_parts = string_end_time.split(":").collect{ |y| y.to_i }
end_time = Time.new(Time.now.year, Time.now.month, Time.now.day, end_time_parts[0], end_time_parts[1], end_time_parts[2])
p end_time

p duration_seconds = end_time.to_i - start_time.to_i

NOTE: Some code refactoring is needed to extract a function to create time from HH:MM:SS, I have duplicate code

Output of above code will be

2015-07-14 15:00:12 +0530
2015-07-14 19:32:12 +0530
16320
[Finished in 0.1s]

Upvotes: 1

Nic Nilov
Nic Nilov

Reputation: 5156

You came pretty close, this code does that:

start_time = '15:00:12'
end_time = '19:32:12'
a = Time.parse(start_time)
b = Time.parse(end_time)
duration_seconds = a - b

The Time.parse method converts string to a Time instance. It understands some but not all formats a time string can have so you'd probably want to validate the input. See Ruby docs for more details.

Upvotes: 1

Related Questions