Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a negative TimeSpan

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.

like image 606
Corey Downie Avatar asked Jul 11 '10 17:07

Corey Downie


People also ask

What is the format of a TimeSpan?

"c" is the default TimeSpan format string; the TimeSpan. ToString() method formats a time interval value by using the "c" format string. TimeSpan also supports the "t" and "T" standard format strings, which are identical in behavior to the "c" standard format string.

How to format Time span in c#?

You can format a TimeSpan in the hh: mm: ss format in C#.


2 Answers

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. :(

like image 161
Will A Avatar answered Sep 21 '22 05:09

Will A


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() 
like image 34
Hans Olsson Avatar answered Sep 23 '22 05:09

Hans Olsson