I take the difference between the two DateTime fields and save them in a TimeSpan variable. Now I need to round TimeSpan with the following rules:
if the minutes in TimeSpan are less than 30, then the minutes and seconds should be set to zero. If the minutes in TimeSpan are equal to or greater than 30, then the hours should be increased by 1, and the minutes and seconds should be set to zero.
TimeSpan can also be a negative value, so in this case I need to keep the sign.
I could fulfill the requirement if TimeSpan was not a negative value, although I wrote code that I do not like with its inefficiency, since it is more cumbersome.
Please suggest me a simpler and more efficient method.
Respectfully,
This is my code that works great when TimeSpan is not a negative value.
TimeSpan time_span = endTime.Subtract(startTime); TimeSpan time_span1; if (time_span.Minutes >= 30) { time_span1 = new TimeSpan(time_span.Hours + 1, 0, 0); } else { time_span1 = new TimeSpan(time_span.Hours, 0, 0); }
time_span1 will contain the result.
source share