How can I String.Format a TimeSpan object with a custom format in .NET?
Solution 1
Please note: this answer is for .Net 4.0 and above. If you want to format a TimeSpan in .Net 3.5 or below please see JohannesH's answer.
Custom TimeSpan format strings were introduced in .Net 4.0. You can find a full reference of available format specifiers at the MSDN Custom TimeSpan Format Strings page.
Here's an example timespan format string:
string.Format("{0:hh\\:mm\\:ss}", myTimeSpan); //example output 15:36:15
(UPDATE) and here is an example using C# 6 string interpolation:
$"{myTimeSpan:hh\\:mm\\:ss}"; //example output 15:36:15
You need to escape the ":" character with a "\" (which itself must be escaped unless you're using a verbatim string).
This excerpt from the MSDN Custom TimeSpan Format Strings page explains about escaping the ":" and "." characters in a format string:
The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.
Solution 2
For .NET 3.5 and lower 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
For .NET 4.0 and above, see DoctaJonez answer.
Solution 3
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.
Solution 4
Simple. Use TimeSpan.ToString
with c, g or G. More information at MSDN
Solution 5
I would go with
myTimeSpan.ToString("hh\\:mm\\:ss");
Related videos on Youtube
Hosam Aly
I'm interested in developing top quality software, optimizing performance, refactoring code, and learning about core computer science topics. For more information about me, please check my LinkedIn profile. I'm currently available for contracts, preferably using Scala or Ruby (outside finance, media, fashion, and advertising).
Updated on June 02, 2021Comments
-
Hosam Aly almost 3 years
What is the recommended way of formatting
TimeSpan
objects into a string with a custom format? -
tvanfosson about 15 yearsThis 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.
-
Hosam Aly about 15 yearsYes, 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.
-
JohannesH about 15 yearsSure, 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 about 15 yearsJust remember that if the TimeSpan is equal to or more than 24 hours you will get incorrect formatting.
-
Hosam Aly over 13 yearsThank 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.
-
codeulike over 13 yearsYou need to cast the myTimeSpan.TotalHours to an int - otherwise it might get rounded-up. See JohannesH's answer
-
Doctor Jones almost 13 years@Andrei Rinea: Correct, as stated at the start of my second paragraph ".Net 4 allows you to use custom format strings with Timespan".
-
Andrei Rînea almost 13 yearsYeah I saw that, just trying to point out to other people. I tried it in 3.5 hoping it's not a v4 only feature.
-
NeverHopeless over 11 yearsDoes it return correct value ? Dim ts As New TimeSpan(11, 22, 30, 30):Dim sss As String = New DateTime(ts.Ticks).ToString("dd.hh:mm:ss")
-
Edward over 10 yearsEquivalent way, but more succinct: myTimeSpan.ToString("hh\\mm\\ss") (As noted above, works only in .Net 4.0 and above).
-
Doctor Jones over 10 years@Edward, that's not quite right. In your example you're escaping the first m and the first s, so with an input of
myTimeSpan = new TimeSpan(15, 35, 54);
the statementmyTimeSpan .ToString("hh\\mm\\ss");
will result in15m35s54
. I don't think that's what you intended as it'll place an m after your hours and an s after your minutes. -
Edward over 10 years@Doctor Jones - Thank you! I meant myTimeSpan.ToString("h\\hm\\ms\\s"); or myTimeSpan.ToString(@"h\hm\ms\s"); which gives 15h35m54s
-
Hosam Aly about 10 yearsNow there is a much better way to write this! Try to refactor all the common operations, and you can make this code look much, much better.
-
Neil over 8 yearsIf you write software that needs to be translated, then this is pretty much the way to go. The standard TimeSpan.ToString() is just too clunky for normal end users to understand, especially when the span if over a day.
-
Zoltan Tirinda about 8 yearsjust be careful with this solution, because it will not work correctly when the Hours part is more than 24
-
panpawel about 8 years@Hosam Aly; I'm learning all the time, do you care to post your improved code?
-
Hosam Aly about 8 years
String timeComponent(int value, String name) { return value > 0 ? value + " " + name + (value > 1 ? "s" : ""); }
Call that for each component (e.g.timeComponent(sp.Days, "day")
), then useString.join
to insert the spaces. -
Xilmiki about 8 yearsSimple and clean! an alternative is @"hh\:mm\:ss"
-
Harvey Kwok over 7 yearsThis solution is not quite right if your TimeSpan has day. @JohannesH solution works better
-
QuarK over 5 yearsHow can I include days in
"hh"
using C# 6 string interpolation? -
Doctor Jones over 5 years@QuarK, there is no custom format specifier that does that, they all give you the hours that are not counted as part of days. You could do this instead though
$"{myTimeSpan.TotalHours}:{myTimeSpan:mm\\:ss}"
. From a user point of view, it might be better to output the days though, nobody wants to mentally figure out how many days are in 200+ hours. -
Arad over 3 yearsWhy not just
.ToString(@"hh\:mm\:ss")
? Isn't that simpler to understand? -
GER over 3 years@Arad That does seem much easier! Wonder why I wrote this answer...
-
Kappacake over 2 yearsWhat language is
:#0:;;\\
? Where can I read about it?