Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan ToString format

Tags:

c#

.net

Just curious, is there a format string I can use to output something like "5h 3m 30s"?

eg. (obviously wrong)

myTimeSpan.ToString("hh mm ss") 
like image 636
Aximili Avatar asked Jun 18 '12 06:06

Aximili


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 do you convert TimeSpan to hours?

A TimeSpan value can be represented as [-]d. hh:mm:ss. ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. The value of the Hours property is the hours component, hh.

What is TimeSpan value?

A TimeSpan value represents a time interval and can be expressed as a particular number of days, hours, minutes, seconds, and milliseconds.

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

Try:

myTimeSpan.ToString("h'h 'm'm 's's'") 

(Note that even spaces need to be quoted - that's what was wrong with my first attempt.)

I'm assuming you're using .NET 4, of course - before that, TimeSpan didn't support custom format strings.

EDIT: As noted, this won't work beyond 24 hours. Also note that alternatives are available via Noda Time too :)

like image 141
Jon Skeet Avatar answered Oct 03 '22 04:10

Jon Skeet