'How to return time in integer method? (C#) [closed]

Using the C# language, have the function StringChallenge(num) take the num

  • parameter being passed and return the number of hours and minutes the parameter *
  • converts to (ie. if num = 63 then the output should be 1:3). Separate the number *
  • of hours and minutes with a colon.

The question above. Problem is how to convert time with colon as return in integer function?

  using System;    
  class MainClass {
  
      
  public static int StringChallenge(int num) {
      
  // code goes here  
  int hour=0;
  int min=0;
  if (num<60)
  {
    
    min = num;
     }
  if (num>60)
  {
    min = num % 60;
    hour = num / 60;
   
  }
  
  return num ;
  
    }
  
    static void Main() {  
      // keep this function call here
      Console.WriteLine(StringChallenge(Console.ReadLine()));
    } 
  
  }


Solution 1:[1]

Let TimeSpan do the work for you:

int num = 60;
TimeSpan ts = TimeSpan.FromMinutes(num);
string formatted = ts.ToString(@"hh\:mm");

which outputs a string like

01:00

To change the format, different patterns can be used. Check out the documentation on this if necessary.

Solution 2:[2]

Here I have taken the method:

public static string StringChallenge(int minute)
{
    return $"{minute / 60}:{minute % 60}";
}

from a 59 turns into "0:59"

from a 60 turns into "1:0"

from a 61 turns into"1:1"

Solution 3:[3]

In general case, I can see two problems here:

  • Large num, say num = 1600, we want 26:40, not 1 day 2:40
  • Negative numbers: we want -12:30, not -12:30

Code

// Note, that we should return string, not int
// d2 - formatting - to have leading zeroes, i.e. 5:01 instead of 5:1
public static string StringChallenge(int num) =>
  $"{num / 60}:{Math.Abs(num % 60):d2}";

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Schecher_1
Solution 3 Dmitry Bychenko