Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create method for 24 hour time format

I am trying to create C# method with two int arguments

public void Time(int hours, int minutes)

which satisfies all the following Test Cases:

Time(11, 7), returns: "11:07"
Time(24, 0), returns: "00:00"
Time(26, 0), returns: "02:00"
Time(0, 160), returns "02:40" (since 160 minutes = 2 hours and 40 minutes)
Time(-1, 0), returns: "23:00"  (negative number - counterclockwise)
Time(1, -40), returns: "00:20"
Time(-25, -160), returns: "20:20" 

My inadequate attempt was this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if (hours > 23)
{
    hours %= 24; 
}

if (minutes > 59)
{
    minutes %= 60;
}

 

But this barely satisfied first,second and third conditions only.

>Solution :

Don’t reinvent the wheel – use TimeSpan instead:

public void Time(int hours, int minutes)
{
    var time = new TimeSpan(hours, minutes, 0);
    Console.WriteLine((DateTime.Today + time).ToString("HH:mm"));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading