Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan FormatString with optional hours

Tags:

c#

asp.net

I have a timespan, ts, that has mostly minutes and seconds, but sometimes hours. I'd like ts to return a formatted string that'll give the following results:

3:30 (hours not displayed, showing only full minutes)
13:30 
1:13:30 (shows only full hours instead of 01:13:30)

So far I have:

string TimeSpanText = string.Format("{0:h\\:mm\\:ss}", MyTimeSpan);

but it's not giving the above results. How can I achieve the results I want?

like image 755
frenchie Avatar asked Jan 17 '11 02:01

frenchie


People also ask

What is TimeSpan format?

A TimeSpan format string defines the string representation of a TimeSpan value that results from a formatting operation. A custom format string consists of one or more custom TimeSpan format specifiers along with any number of literal characters.

What is TimeSpan C#?

C# TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds. C# TimeSpan is used to compare two C# DateTime objects to find the difference between two dates.


1 Answers

Maybe you want something like

string TimeSpanText = string.Format(
    MyTimeSpan.TotalHours >= 1 ? @"{0:h\:mm\:ss}" : @"{0:mm\:ss}",
    MyTimeSpan); 
like image 114
Gabe Avatar answered Oct 10 '22 15:10

Gabe