Calculating the Difference Between Two Time Periods in Ruby
Ruby is a dynamic, object-oriented programming language well-known for its simplicity and productivity.
It’s widely used in web development, especially with the Ruby on Rails
framework. When working with time-sensitive features—such as logs, schedules, or billing—you may need to calculate the duration between two time points.
In this sub-article, we’ll implement a Ruby program that calculates the difference between two times using the built-in Time
class.
This example follows the same logic as our lead C article but tailored to Ruby's concise and expressive syntax.
Ruby Program: Calculate the Difference Between Two Time Periods
# DIFFERENCE BETWEEN TWO TIME PERIODS in Ruby using Time class
# Step-1 Define the start and end time
start_time = Time.new(2025, 12, 1, 7, 30, 10)
end_time = Time.new(2025, 12, 9, 14, 55, 50)
# Step-2 Calculate the difference in seconds
difference_in_seconds = end_time - start_time
# Step-3 Convert seconds to hours, minutes, and seconds
hours = (difference_in_seconds / 3600).to_i
minutes = ((difference_in_seconds % 3600) / 60).to_i
seconds = (difference_in_seconds % 60).to_i
# Step-4 Display the result
puts "\nTIME DIFFERENCE: #{hours} HOURS, #{minutes} MINUTES, #{seconds} SECONDS"
Output
TIME DIFFERENCE: 199 HOURS, 25 MINUTES, 40 SECONDS
Explanation
-
Ruby’s
Time.new
initializes time with year, month, day, hour, minute, and second. -
Subtracting two
Time
objects returns the difference in seconds. -
We then calculate the equivalent hours, minutes, and seconds for easy readability.
This method is particularly helpful in Ruby-based automation tools, time-tracking systems, or scheduling applications.
???? Extra Metric: Time Difference in Days
Ruby also makes it easy to calculate the total difference in days:
days = (difference_in_seconds / (24 * 3600)).to_i
puts "TOTAL DAYS: #{days}"
Output
TOTAL DAYS: 8
This metric is useful for billing cycles, service usage periods, or long-duration logs.