Lesson 3
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.

Ruby
1time = "12:34:56" 2time_parts = time.split(":").map(&:to_i) 3 4puts time_parts.inspect

This produces:

Ruby
1[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:

Ruby
1seconds_since_start = time_parts[0] * 3600 + time_parts[1] * 60 + time_parts[2] 2 3puts 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.

Ruby
1seconds_to_add = 123 2total_seconds = (seconds_since_start + seconds_to_add) % (24 * 3600) 3 4puts 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:

Ruby
1hours = total_seconds / 3600 2remainder = total_seconds % 3600 3minutes = remainder / 60 4seconds = remainder % 60 5 6puts [hours, minutes, seconds].inspect

This produces:

Ruby
1[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:

Ruby
1formatted_time = format('%02d:%02d:%02d', hours, minutes, seconds) 2 3puts formatted_time

For this example, the output is:

Ruby
1"12:36:59"
Bringing Everything Together

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

Ruby
1def parse_and_add_seconds(time, seconds_to_add) 2 # Split the time into hours, minutes, and seconds 3 time_parts = time.split(":").map(&:to_i) 4 5 # Convert time to total seconds 6 seconds_since_start = time_parts[0] * 3600 + time_parts[1] * 60 + time_parts[2] 7 8 # Add the extra seconds and wrap around using modulus 9 total_seconds = (seconds_since_start + seconds_to_add) % (24 * 3600) 10 11 # Convert total seconds back to hours, minutes, and seconds 12 hours = total_seconds / 3600 13 remainder = total_seconds % 3600 14 minutes = remainder / 60 15 seconds = remainder % 60 16 17 # Format and return the result 18 format('%02d:%02d:%02d', hours, minutes, seconds) 19end 20 21# Example Usage 22puts parse_and_add_seconds("12:34:56", 123) # Outputs: "12:36:59" 23puts parse_and_add_seconds("23:59:59", 2) # Outputs: "00:00:01" 24puts 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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.