How can I String.Format a TimeSpan object with a custom format in .NET?

137,264

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");
Share:
137,264

Related videos on Youtube

Hosam Aly
Author by

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, 2021

Comments

  • Hosam Aly
    Hosam Aly almost 3 years

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

  • tvanfosson
    tvanfosson about 15 years
    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.
  • Hosam Aly
    Hosam Aly about 15 years
    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.
  • JohannesH
    JohannesH about 15 years
    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
    JohannesH about 15 years
    Just remember that if the TimeSpan is equal to or more than 24 hours you will get incorrect formatting.
  • Hosam Aly
    Hosam Aly over 13 years
    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.
  • codeulike
    codeulike over 13 years
    You need to cast the myTimeSpan.TotalHours to an int - otherwise it might get rounded-up. See JohannesH's answer
  • Doctor Jones
    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
    Andrei Rînea almost 13 years
    Yeah 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
    NeverHopeless over 11 years
    Does 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
    Edward over 10 years
    Equivalent way, but more succinct: myTimeSpan.ToString("hh\\mm\\ss") (As noted above, works only in .Net 4.0 and above).
  • Doctor Jones
    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 statement myTimeSpan .ToString("hh\\mm\\ss"); will result in 15m35s54. 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
    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
    Hosam Aly about 10 years
    Now 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
    Neil over 8 years
    If 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
    Zoltan Tirinda about 8 years
    just be careful with this solution, because it will not work correctly when the Hours part is more than 24
  • panpawel
    panpawel about 8 years
    @Hosam Aly; I'm learning all the time, do you care to post your improved code?
  • Hosam Aly
    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 use String.join to insert the spaces.
  • Xilmiki
    Xilmiki about 8 years
    Simple and clean! an alternative is @"hh\:mm\:ss"
  • Harvey Kwok
    Harvey Kwok over 7 years
    This solution is not quite right if your TimeSpan has day. @JohannesH solution works better
  • QuarK
    QuarK over 5 years
    How can I include days in "hh" using C# 6 string interpolation?
  • Doctor Jones
    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
    Arad over 3 years
    Why not just .ToString(@"hh\:mm\:ss")? Isn't that simpler to understand?
  • GER
    GER over 3 years
    @Arad That does seem much easier! Wonder why I wrote this answer...
  • Kappacake
    Kappacake over 2 years
    What language is :#0:;;\\ ? Where can I read about it?