views:

9946

answers:

7

What is the recommended way of formatting TimeSpan objects into a string with a custom format?

+14  A: 

One way is to create a DateTime object and use it for formatting:

new DateTime(myTimeSpan.Ticks).ToString(myCustomFormat)

// or using String.Format:
String.Format("{0:HHmmss}", new DateTime(myTimeSpan.Ticks))

This is the way I know. I hope someone can suggest a better way.

Hosam Aly
This is really only going to work if the TimeSpan is less than a day. That might not be a such a terrible restriction, but it keeps it from being a general solution.
tvanfosson
Good point @tvanfosson. Thank you.
Hosam Aly
+18  A: 

You could use:

string.Format ("{0:00}:{1:00}:{2:00}", (int)myTimeSpan.TotalHours, myTimeSpan.Minutes, myTimeSpan.Seconds);

Code taken from a Jon Skeet answer on bytes

JohannesH
Yes, thank you. But I think that DateTime approach is more customizable, as it would work for any time format supported by DateTime. This approach is hard to use for showing AM/PM for example.
Hosam Aly
Sure, TimeSpan is meant to represents a period of time, not a time of day (Even though the DateTime.Now.TimeOfDay property would have you believe otherwise). If you need to represent a specific time of day I suggest you continue using the DateTime class.
JohannesH
Just remember that if the TimeSpan is equal to or more than 24 hours you will get incorrect formatting.
JohannesH
If you pass 2 hours and 40 minutes it will display 03:40 since Totalhours will be 2.67
jvanderh
You need to cast the myTimeSpan.TotalHours to an int or the like - this is actually done in Skeet's original post, so maybe it got wiped by SOF post formatting
fostandy
A: 

Maybe this helps ? .NET Format String 102: DateTime Format String

esjr
TimeSpan != DateTime.
Richard
+1  A: 
     string ret = string.Format("{0}{1:00}:{2:00}", (info.Tick.Hours > 0 ? info.Tick.Hours.ToString("00") + ":" : ""), info.Tick.Minutes, info.Tick.Seconds);
radioman
+1  A: 

This is awesone one:

string.Format ("{0:00}:{1:00}:{2:00}", myTimeSpan.TotalHours, myTimeSpan.Minutes, myTimeSpan.Seconds);

Harpal
You need to cast the myTimeSpan.TotalHours to an int - otherwise it might get rounded-up. See JohannesH's answer
codeulike
A: 

greate code it is working fine thanks

Amit
+2  A: 

Simple. Use TimeSpan.ToString with c, g or G. More information at http://msdn.microsoft.com/en-us/library/ee372286.aspx

KKK
Thank you for your answer. This method is apparently new in .NET 4, and did not exist when the question was asked. It also does not support custom formats. Nevertheless, it's a valuable addition to the answers to this questions. Thanks again.
Hosam Aly