Formatting a negative TimeSpan

It seems like you're stuck with that code, but if so, this seems like a great time to write an extesion method, that way you can make your code clearer and you don't have to repeat that code in multiple places, so something like:

Module Extensions
    <System.Runtime.CompilerServices.Extension()> _
    Public Function HoursAndMinutes(ByVal ts As TimeSpan) As String
        Return If(ts < TimeSpan.Zero, "-", "") & ts.ToString("hh\:mm")
    End Function
End Module

And then you could just call it as:

ts.HoursAndMinutes()

I agree with Will. MSDN and Reflector both indicate that you're out of luck. The best you're gonna get is to either use what you have, write your own IFormatProvider, or use one of the standard formats for timespan like "g".


I've used .Net Reflector on TimeSpan.ToString(...) and it really doesn't look like it supports any form of negative prefix on custom formats - so I think you're out of luck when it comes to getting it to work for you as above. :(