Format time greater than 24 hours

643 views Asked by At

I have a textbox were the user can enter in the estimate hours, for example it could be 150 hours. How do I format this time? The time automatically formats to 00:00:00 so If I enter in 150 hours it changes to 34.22:59:59

TimeSpan tmpEstimate;
TimeSpan? TimeEstimate;

if (TimeSpan.TryParse(txtEstimateHrs.Text, out tmpEstimate))
    TimeEstimate = tmpEstimate;
else
   TimeEstimate = null;

The user will only enter in the hours so I don't need to format the minutes or seconds but the field could also be left blank so it needs to accept a null time to

2

There are 2 answers

8
Backs On

Maybe it's better to use double value for input, not time?

TimeSpan? TimeEstimate = null;
double tmpEstimate; 
if (double.TryParse(txtEstimateHrs.Text, out tmpEstimate)) 
{ 
    TimeEstimate = TimeSpan.FromHours(tmpEstimate); 
}

OR

double? TimeEstimate = null;
double tmpEstimate; 
if (double.TryParse(txtEstimateHrs.Text, out tmpEstimate)) 
{ 
    TimeEstimate = tmpEstimate; 
}
0
LordWilmore On

If you're only interested in the hours then take a look at TimeSpan.FromHours(), which takes a number of hours and makes you a TimeSpan object for that value only. If the value is null then you can handle that separately.