Handle negative time spans

fr0xx picture fr0xx · Jun 19, 2009 · Viewed 64.5k times · Source

In my output of a grid, I calculate a TimeSpan and take its TotalHours. e.g.

(Eval("WorkedHours") - Eval("BadgedHours")).TotalHours

The goal is to show the TotalHours as 39:44, so I need to convert the value from 7.5 to 07:30. This is no problem... unless it's negative!

I can create a TimeSpan object from Hours with

TimeSpan.FromHours( (Eval("WorkedHours") - Eval("BadgedHours")).TotalHours)

If it's negative, I can't convert it to a DateTime to use the .ToString("HH:mm") method, and the TimeSpan object does not support the format string.

Answer

Jared picture Jared · Nov 27, 2011

Isn't there a TimeSpan.Duration method? I think this would handle what you are trying to do.