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

后端 未结 19 1273
情深已故
情深已故 2020-11-22 12:25

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

相关标签:
19条回答
  • 2020-11-22 12:44

    I would go with

    myTimeSpan.ToString("hh\\:mm\\:ss");
    
    0 讨论(0)
  • 2020-11-22 12:44

    This is awesome one:

    string.Format("{0:00}:{1:00}:{2:00}",
                   (int)myTimeSpan.TotalHours,
                   myTimeSpan.Minutes,
                   myTimeSpan.Seconds);
    
    0 讨论(0)
  • 2020-11-22 12:45
    Dim duration As New TimeSpan(1, 12, 23, 62)
    
    DEBUG.WriteLine("Time of Travel: " + duration.ToString("dd\.hh\:mm\:ss"))
    

    It works for Framework 4

    http://msdn.microsoft.com/en-us/library/ee372287.aspx

    0 讨论(0)
  • 2020-11-22 12:48

    Personally, I like this approach:

    TimeSpan ts = ...;
    string.Format("{0:%d}d {0:%h}h {0:%m}m {0:%s}s", ts);
    

    You can make this as custom as you like with no problems:

    string.Format("{0:%d}days {0:%h}hours {0:%m}min {0:%s}sec", ts);
    string.Format("{0:%d}d {0:%h}h {0:%m}' {0:%s}''", ts);
    
    0 讨论(0)
  • 2020-11-22 12:50

    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.

    0 讨论(0)
  • 2020-11-22 12:51

    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.

    0 讨论(0)
提交回复
热议问题