Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Work out min and hours

Tags:

c#

.net

datetime

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#?

like image 973
MartGriff Avatar asked Mar 03 '09 13:03

MartGriff


1 Answers

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.

like image 50
froh42 Avatar answered Nov 13 '22 21:11

froh42