Time Manipulation and String Operations

Introduction

Welcome! Today, we’ll explore a fascinating and practical task that combines string operations, type conversions, and arithmetic calculations in Ruby. You’ll learn how to manipulate and calculate time data—a skill that's applicable in many real-world scenarios.

By the end of this lesson, you’ll know how to add a given number of seconds to a time in HH:MM:SS format and return the updated time. Let’s dive in!

Task Statement and Description

Your goal is to write a Ruby method that performs the following steps:

  1. Take an input time in the HH:MM:SS format, where:
    • HH represents hours (00–23),
    • MM represents minutes (00–59),
    • SS represents seconds (00–59).
  2. Add a specified number of seconds to this time.
  3. Return the new time, formatted as HH:MM:SS.

For example, if the input time is "05:10:30" and the number of seconds to add is 123, the output should be "05:12:33". This is because 123 seconds translate to 2 minutes and 3 seconds, which are added to the original time.

Key Details to remember:

  • The input time will always be valid and follow the HH:MM:SS format.
  • The output should also follow the same format.
  • If the number of seconds causes the time to roll over past midnight, ensure the time wraps around correctly (e.g., adding 86400 seconds, a full day, results in the same time).

Let’s break this problem into manageable steps and solve it!

Step 1: Parse the Time String

The first step is to extract the hours, minutes, and seconds from the input string. We can use Ruby’s split method to divide the string by the : delimiter and convert each part to an integer.

time = "12:34:56"
time_parts = time.split(":").map(&:to_i)

puts time_parts.inspect

This produces:

[12, 34, 56]

Now, we have the hours, minutes, and seconds as integers, ready for calculations.

Step 2: Convert Time to Total Seconds

To simplify addition, convert the time into the total number of seconds since midnight. This allows us to work with a single number rather than juggling hours, minutes, and seconds separately.

The formula for calculating total seconds is:

  • total_seconds = hours * 3600 + minutes * 60 + seconds

Here’s how it looks in Ruby:

seconds_since_start = time_parts[0] * 3600 + time_parts[1] * 60 + time_parts[2]

puts seconds_since_start

For "12:34:56", this calculates 45296 seconds since midnight.

Step 3: Add the Extra Seconds

Add the given number of seconds to seconds_since_start. If the result exceeds the total number of seconds in a day (86400), use the modulus operator (%) to wrap it around. This ensures the time remains within a 24-hour format.

seconds_to_add = 123
total_seconds = (seconds_since_start + seconds_to_add) % (24 * 3600)

puts total_seconds

For this example, the result is 45419 seconds.

Step 4: Convert Total Seconds Back to Time

Now, reverse the conversion to calculate the new hours, minutes, and seconds. Use division and modulus operations:

hours = total_seconds / 3600
remainder = total_seconds % 3600
minutes = remainder / 60
seconds = remainder % 60

puts [hours, minutes, seconds].inspect

This produces:

[12, 36, 59]

Step 5: Format the Output Time

Format the result into the HH:MM:SS format. Use Ruby’s format method to ensure each component is zero-padded to two digits:

formatted_time = format('%02d:%02d:%02d', hours, minutes, seconds)

puts formatted_time

For this example, the output is:

"12:36:59"

Bringing Everything Together

Here’s the complete Ruby method combining all of the steps above:

def parse_and_add_seconds(time, seconds_to_add)
  # Split the time into hours, minutes, and seconds
  time_parts = time.split(":").map(&:to_i)
  
  # Convert time to total seconds
  seconds_since_start = time_parts[0] * 3600 + time_parts[1] * 60 + time_parts[2]
  
  # Add the extra seconds and wrap around using modulus
  total_seconds = (seconds_since_start + seconds_to_add) % (24 * 3600)
  
  # Convert total seconds back to hours, minutes, and seconds
  hours = total_seconds / 3600
  remainder = total_seconds % 3600
  minutes = remainder / 60
  seconds = remainder % 60
  
  # Format and return the result
  format('%02d:%02d:%02d', hours, minutes, seconds)
end

# Example Usage
puts parse_and_add_seconds("12:34:56", 123)  # Outputs: "12:36:59"
puts parse_and_add_seconds("23:59:59", 2)    # Outputs: "00:00:01"
puts parse_and_add_seconds("00:00:00", 86400) # Outputs: "00:00:00"

Lesson Summary

Congratulations! In this lesson, you mastered the process of parsing time strings, performing arithmetic with time, and formatting the result back into a user-friendly string. These skills are invaluable when working with time-sensitive applications.

As a next step, consider experimenting with variations of this problem—such as subtracting seconds or calculating the difference between two times. Each challenge strengthens your Ruby expertise. Keep learning, keep coding, and enjoy the journey!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal