How to get the difference between two dates in seconds with Ruby

1 Answer

0 votes
require 'time'

# Calculates the total number of seconds between two Time objects.
# 
# @param start_time [Time] The starting date and time.
# @param end_time [Time] The ending date and time.
# @return [Float] The total number of seconds, including fractional seconds.
def get_seconds_between(start_time, end_time)
  # Subtracting one Time object from another directly returns the difference in seconds as a Float
  end_time - start_time
end

# --- Complete Program Demonstration ---
def main
  # Define two Time instances in UTC (best practice for server and application consistency)
  start_time = Time.utc(2026, 10, 27, 12, 0, 0)
  end_time   = Time.utc(2026, 10, 27, 12, 5, 30)

  # Call the function to calculate the seconds between the two dates
  total_seconds = get_seconds_between(start_time, end_time)

  # Output the results to the console using ISO 8601 formatting
  puts "Start Time: #{start_time.iso8601}"
  puts "End Time:   #{end_time.iso8601}"
  puts "Total Seconds Between: #{total_seconds}"
end

# Execute the program
main()


# run:
#
# Start Time: 2026-10-27T12:00:00Z
# End Time:   2026-10-27T12:05:30Z
# Total Seconds Between: 330.0
# 

 



answered Oct 27 by avibootz
...