Time Parsing and Type Conversion in C#

Introduction

Welcome! In today's lesson, we will explore the practical application of string operations and type conversions in C#. These concepts are essential and are utilized in various programming scenarios. We'll look at a real-world example: time parsing. 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 calculate this using C#. Let's start!

Task Statement and Description

Imagine this: You receive a time formatted as a string in HH:MM:SS, where HH, MM, and SS represent the hour, minute, and second, respectively. Additionally, you are given an integer representing a number of seconds. Your task is to compute 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 convert to 2 minutes and 3 seconds.

Take note of these points when resolving this task:

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

Let's go ahead and break down how to accomplish this in our step-by-step solution guide.

Step-by-Step Solution Building: Step 1

Our initial step involves parsing the input time string. From this string, we'll extract the hours, minutes, and seconds as integer values for further calculations. In C#, we can utilize the Split() method along with int.Parse() or Convert.ToInt32() to divide the string at ":" and convert each substring into an integer:

string time = "12:34:56";
string[] timeParts = time.Split(':');
int hours = int.Parse(timeParts[0]);
int minutes = int.Parse(timeParts[1]);
int seconds = int.Parse(timeParts[2]);

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 as integers, we can easily calculate the total number of seconds elapsed since the start of the day. Here's the logic behind it:

  • 1 hour comprises 3,600 seconds, so we multiply the number of hours by 3,600.
  • 1 minute comprises 60 seconds, so we multiply the number of minutes by 60.
  • The count of seconds remains unchanged.

In C#, we can write the following code:

int secondsSinceStart = hours * 3600 + minutes * 60 + seconds;

Your function should now 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