What is the recommended way of formatting TimeSpan
objects into a string with a custom format?
views:
9946answers:
7
+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
2009-02-22 13:00:34
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
2009-02-22 13:17:33
Good point @tvanfosson. Thank you.
Hosam Aly
2009-02-22 13:30:45
+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
2009-02-22 13:06:56
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
2009-02-22 13:21:29
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
2009-02-22 13:41:23
Just remember that if the TimeSpan is equal to or more than 24 hours you will get incorrect formatting.
JohannesH
2009-02-22 13:42:19
If you pass 2 hours and 40 minutes it will display 03:40 since Totalhours will be 2.67
jvanderh
2009-12-22 14:36:22
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
2010-05-27 02:00:05
+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
2009-10-02 08:16:48
+1
A:
This is awesone one:
string.Format ("{0:00}:{1:00}:{2:00}", myTimeSpan.TotalHours, myTimeSpan.Minutes, myTimeSpan.Seconds);
Harpal
2010-04-14 17:11:25
You need to cast the myTimeSpan.TotalHours to an int - otherwise it might get rounded-up. See JohannesH's answer
codeulike
2010-09-07 13:44:41
+2
A:
Simple. Use TimeSpan.ToString
with c, g or G. More information at http://msdn.microsoft.com/en-us/library/ee372286.aspx
KKK
2010-08-09 18:26:52
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
2010-08-10 19:44:00