Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract from Timespan Totalhours and Minutes

Tags:

c#

timespan

I get from TimeSpan.TotalHours 24,75 hours. How can I convert this to get the full and not roundes hours (=24) plus the minutes (0,75hours = 45 minutes)? So the result should be hours = 24 and minutes = 45

I tried to convert it to string and make substring but I would like to know if there is a better way than this.

string test = Reststunden.TotalHours.ToString().Substring(Reststunden.TotalHours.ToString().IndexOf(","),3).Replace(",", "");
double Minuten = Convert.ToInt16(test) * 0.6;
like image 571
Kᴀτᴢ Avatar asked Dec 06 '22 18:12

Kᴀτᴢ


2 Answers

Well just round the total hours appropriately by casting, and then use the Minutes property:

int hours = (int) timeSpan.TotalHours;
int minutes = timeSpan.Minutes;

If you'll ever have a negative TimeSpan, you should think about what you want the results to be and add appropriate tests - you may well find it doesn't do what you want with the simple code above.

like image 92
Jon Skeet Avatar answered Dec 17 '22 20:12

Jon Skeet


How about:

var ts = TimeSpan.FromHours(24.75);
var h = System.Math.Floor(ts.TotalHours);
var m = (ts.TotalHours - h) * 60;

Or even:

var h = (int) (ts.TotalMinutes / 60);
var m = ts.TotalMinutes % 60;
like image 33
lesscode Avatar answered Dec 17 '22 20:12

lesscode