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.

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