469,955 Members | 2,576 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,955 developers. It's quick & easy.

Create method for 24 hour time format

Important Note: I am not allowed to Use TimeSpan

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

Expand|Select|Wrap|Line Numbers
  1. 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"
4 Weeks Ago #1
2 8879
SioSio
267 256MB
Here is an example that does not use any time-related functions.
Expand|Select|Wrap|Line Numbers
  1.             int h_div, h_rm, m_div, m_rm, i = 0;
  2.             while(minutes < 0){
  3.                 minutes = minutes + 60;
  4.                 i++;
  5.             }
  6.             hours = hours - i;
  7.             while(hours < 0) hours = hours + 24;
  8.             m_div = Math.DivRem(minutes, 60, out m_rm);
  9.             h_div = Math.DivRem(hours + m_div, 24, out h_rm);
  10.             Console.WriteLine(String.Format("{0:D2}:{1:D2}", h_rm, m_rm));
3 Weeks Ago #2
cactusdata
188 Expert 128KB
You can use DateTime and a one-liner:

Expand|Select|Wrap|Line Numbers
  1. int hours = -25;
  2. int minutes = -160;
  3.  
  4. string textTime = DateTime.Today.AddHours(hours).AddMinutes(minutes).ToString("HH:mm");
  5.  
  6. Console.WriteLine(textTime);
3 Weeks Ago #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

7 posts views Thread by Robert Misiak | last post: by
3 posts views Thread by Just D | last post: by
4 posts views Thread by PinkBishop | last post: by
6 posts views Thread by Dogmar Hoffman | last post: by
5 posts views Thread by Julia | last post: by
1 post views Thread by kalisha | last post: by
23 posts views Thread by tatata9999 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.