Formatting a negative TimeSpan

Viewed 10285

I'm doing some math with the Timespans in .Net, and occasionally the sum results in a negative Timespan. When I display the result I am having trouble formatting it to include the negative indicator.

Dim ts as New Timespan(-10,0,0)

ts.ToString()

This will display "-10:00:00", which is good but I don't want to show the seconds so tried this.

ts.ToString("hh\:mm")

This returns "10:00" and has dropped the "-" from the front which is the crux of the issue. My current solution is this:

If(ts < TimeSpan.Zero, "-", "") & ts.ToString("hh\:mm")

but I was hoping to accomplish the same by using only the format string.

7 Answers

After testing different approaches, here is what I did:

Public Module TimeExtensions
    <Extension>
    Public Function ToHourMinute(ByVal time As TimeSpan) As String
        Return $"{If(time < TimeSpan.Zero, "-", "")}{time:hh\:mm}"
    End Function
End Module
Related