Home > other >  Create method for 24 hour time format
Create method for 24 hour time format

Time:12-31

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:

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

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

 

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

CodePudding user response:

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"));
}
  • Related