Introduction

Welcome! In this lesson, we will delve into the practical applications of string operations and type conversions in TypeScript. By leveraging TypeScript's type safety features, we can write robust code that handles time parsing more reliably. Have you ever wondered how to add a specific number of seconds to a given time? By the end of today's session, you'll be equipped to perform this calculation using TypeScript. Let's get started!

Task Statement and Description

Imagine this: You receive a time formatted as a string in HH:MM:SS, where HH, MM, and SS denote the hour, minute, and second, respectively. You are also given an integer representing a number of seconds. Your task is to calculate the new time after adding the provided seconds and output the result in the HH:MM:SS format.

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, since 123 seconds translate to 2 minutes and 3 seconds.

Please note these points when resolving this task:

  • The input time is always a valid time string in the HH:MM:SS format, with HH ranging from 00 to 23 and MM and SS ranging from 00 to 59.
  • The output should be a time in the same format.

Now let's go ahead and break down how to achieve this in our step-by-step solution guide.

Step-by-Step Solution Building: Step 1

Our first step involves parsing the input time string. We aim to extract the hours, minutes, and seconds from this string as integer values for further calculations. In TypeScript, we use the split method to divide the string at ":" and convert each substring into an integer, with type annotations added for clarity:

let time: string = "12:34:56";
let secondsToAdd: number = 10;
let timeParts: string[] = time.split(":");
let hours: number = parseInt(timeParts[0], 10);
let minutes: number = parseInt(timeParts[1], 10);
let seconds: number = parseInt(timeParts[2], 10);

By executing this operation, we've successfully parsed the time string and converted the hours, minutes, and seconds into integers.

Step-by-Step Solution Building: Step 2

Now that we have the hours, minutes, and seconds in integer format, we can efficiently calculate the total number of seconds that have elapsed since the start of the day:

let secondsSinceStart: number = hours * 3600 + minutes * 60 + seconds;

At this point, your function should compute the cumulative number of seconds from the start of the day.

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