Question

I have a minute value and i want to have to 2 string values one with how many hours and the other with the minutes, e.g.:

Value - 121 minutes

string hours = 2
string minutes = 1

Value - 58 minutes

string hours = 0
string minutes = 58

How can I work this out in C#?

Was it helpful?

Solution

var span = System.TimeSpan.FromMinutes(121);
var hours = ((int)span.TotalHours).ToString();     
var minutes = span.Minutes.ToString();

The ToString() is because you asked for string values ...

TotalHours are the complete hours in the TimeSpan, they can be more than 24 (whereas the "Hours" field has a maximum of 24)

Oh, and on second thought: Why use the TimeSpan and not calculate it yourself? Because TimeSpan is already there debugged & tested by Microsoft, it has a nice clean interface (looking at the code you easily see whats going on without having to follow a calculation mentally) and it easily extends to further solutions. (Have the input in seconds? Use TimeSpan.FromSeconds(). Want the days? Use span.TotalDays ...)

Update:

I just noticed mistake in my answer: TotalHours returns a fractional value of all the hours, so we have to truncate it to an integer before converting it to a string.

OTHER TIPS

Use a Timespan struct and its Parse method.

int value = 121;
int hours = value / 60; // 2
int minutes = value % 60; // 1

string strHours = hours.ToString();
string strMinutes = minutes.ToString();
int value = 121;
int hours = value / 60;
int minutes = value % 60;
int value = 121;
TimeSpan timeSpan = TimeSpan.FromMinutes(value);

// gives you the rounded down value of 2
int hours = timeSpan.Hours; 

// gives you the minutes left of the hour
int minutes = value - (hours * 60);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top