197

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

Doctor Jones
  • 21,196
  • 13
  • 77
  • 99
Hosam Aly
  • 41,555
  • 36
  • 141
  • 182

20 Answers20

274

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.

Doctor Jones
  • 21,196
  • 13
  • 77
  • 99
  • 7
    @Andrei Rinea: Correct, as stated at the start of my second paragraph ".Net 4 allows you to use custom format strings with Timespan". – Doctor Jones Jul 13 '11 at 09:49
  • 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. – Andrei Rînea Jul 13 '11 at 12:38
  • Equivalent way, but more succinct: myTimeSpan.ToString("hh\\mm\\ss") (As noted above, works only in .Net 4.0 and above). – Edward Sep 02 '13 at 06:48
  • 1
    @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. – Doctor Jones Sep 02 '13 at 09:26
  • 1
    @Doctor Jones - Thank you! I meant myTimeSpan.ToString("h\\hm\\ms\\s"); or myTimeSpan.ToString(@"h\hm\ms\s"); which gives 15h35m54s – Edward Sep 08 '13 at 07:30
  • 2
    just be careful with this solution, because it will not work correctly when the Hours part is more than 24 – Zoltan Tirinda Mar 17 '16 at 21:15
  • This solution is not quite right if your TimeSpan has day. @JohannesH solution works better – Harvey Kwok Oct 08 '16 at 02:08
  • How can I include days in `"hh"` using C# 6 string interpolation? – QuarK Nov 14 '18 at 14:47
  • 1
    @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. – Doctor Jones Nov 14 '18 at 16:33
94

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.

Community
  • 1
  • 1
JohannesH
  • 6,430
  • 5
  • 37
  • 71
  • 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 Feb 22 '09 at 13:21
  • 1
    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 Feb 22 '09 at 13:41
  • 7
    Just remember that if the TimeSpan is equal to or more than 24 hours you will get incorrect formatting. – JohannesH Feb 22 '09 at 13:42
31

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
  • 41,555
  • 36
  • 141
  • 182
  • 15
    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 Feb 22 '09 at 13:17
  • 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") – NeverHopeless Nov 18 '12 at 22:18
11

Simple. Use TimeSpan.ToString with c, g or G. More information at MSDN

MrMaavin
  • 1,611
  • 2
  • 19
  • 30
KKK
  • 111
  • 1
  • 2
  • 1
    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 Aug 10 '10 at 19:44
9

I would go with

myTimeSpan.ToString("hh\\:mm\\:ss");
Shehab Fawzy
  • 7,148
  • 1
  • 25
  • 18
7

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);
NoOne
  • 3,851
  • 1
  • 40
  • 47
6
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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Enel Almonte
  • 61
  • 1
  • 1
5

This is awesome one:

string.Format("{0:00}:{1:00}:{2:00}",
               (int)myTimeSpan.TotalHours,
               myTimeSpan.Minutes,
               myTimeSpan.Seconds);
sc911
  • 1,130
  • 10
  • 18
Harpal
  • 51
  • 1
  • 1
  • 1
    You need to cast the myTimeSpan.TotalHours to an int - otherwise it might get rounded-up. See JohannesH's answer – codeulike Sep 07 '10 at 13:44
3

You can also go with:

Dim ts As New TimeSpan(35, 21, 59, 59)  '(11, 22, 30, 30)    '
Dim TimeStr1 As String = String.Format("{0:c}", ts)
Dim TimeStr2 As String = New Date(ts.Ticks).ToString("dd.HH:mm:ss")

EDIT:

You can also look at Strings.Format.

    Dim ts As New TimeSpan(23, 30, 59)
    Dim str As String = Strings.Format(New DateTime(ts.Ticks), "H:mm:ss")
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
3
if (timeSpan.TotalDays < 1)
    return timeSpan.ToString(@"hh\:mm\:ss");

return timeSpan.TotalDays < 2
    ? timeSpan.ToString(@"d\ \d\a\y\ hh\:mm\:ss")
    : timeSpan.ToString(@"d\ \d\a\y\s\ hh\:mm\:ss");

All literal characters must be escaped.

Ryan Williams
  • 1,465
  • 15
  • 19
3

This is the approach I used my self with conditional formatting. and I post it here because I think this is clean way.

$"{time.Days:#0:;;\\}{time.Hours:#0:;;\\}{time.Minutes:00:}{time.Seconds:00}"

example of outputs:

00:00 (minimum)

1:43:04 (when we have hours)

15:03:01 (when hours are more than 1 digit)

2:4:22:04 (when we have days.)

The formatting is easy. time.Days:#0:;;\\ the format before ;; is for when value is positive. negative values are ignored. and for zero values we have;;\\ in order to hide it in formatted string. note that the escaped backslash is necessary otherwise it will not format correctly.

Community
  • 1
  • 1
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
3

Here is my extension method:

public static string ToFormattedString(this TimeSpan ts)
{
    const string separator = ", ";

    if (ts.TotalMilliseconds < 1) { return "No time"; }

    return string.Join(separator, new string[]
    {
        ts.Days > 0 ? ts.Days + (ts.Days > 1 ? " days" : " day") : null,
        ts.Hours > 0 ? ts.Hours + (ts.Hours > 1 ? " hours" : " hour") : null,
        ts.Minutes > 0 ? ts.Minutes + (ts.Minutes > 1 ? " minutes" : " minute") : null,
        ts.Seconds > 0 ? ts.Seconds + (ts.Seconds > 1 ? " seconds" : " second") : null,
        ts.Milliseconds > 0 ? ts.Milliseconds + (ts.Milliseconds > 1 ? " milliseconds" : " millisecond") : null,
    }.Where(t => t != null));
}

Example call:

string time = new TimeSpan(3, 14, 15, 0, 65).ToFormattedString();

Output:

3 days, 14 hours, 15 minutes, 65 milliseconds
chviLadislav
  • 1,204
  • 13
  • 15
1

I used the code below. It is long, but still it is one expression, and produces very friendly output, as it does not outputs days, hours, minutes, or seconds if they have value of zero.

In the sample it produces output: "4 days 1 hour 3 seconds".

TimeSpan sp = new TimeSpan(4,1,0,3);
string.Format("{0}{1}{2}{3}", 
        sp.Days > 0 ? ( sp.Days > 1 ? sp.ToString(@"d\ \d\a\y\s\ "): sp.ToString(@"d\ \d\a\y\ ")):string.Empty,
        sp.Hours > 0 ? (sp.Hours > 1 ? sp.ToString(@"h\ \h\o\u\r\s\ ") : sp.ToString(@"h\ \h\o\u\r\ ")):string.Empty,
        sp.Minutes > 0 ? (sp.Minutes > 1 ? sp.ToString(@"m\ \m\i\n\u\t\e\s\ ") :sp.ToString(@"m\ \m\i\n\u\t\e\ ")):string.Empty,
        sp.Seconds > 0 ? (sp.Seconds > 1 ? sp.ToString(@"s\ \s\e\c\o\n\d\s"): sp.ToString(@"s\ \s\e\c\o\n\d\s")):string.Empty);
panpawel
  • 1,782
  • 1
  • 16
  • 17
  • 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. – Hosam Aly Mar 29 '14 at 04:47
  • @Hosam Aly; I'm learning all the time, do you care to post your improved code? – panpawel Apr 01 '16 at 14:04
  • `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. – Hosam Aly Apr 05 '16 at 09:59
1

I use this method. I'm Belgian and speak dutch so plural of hours and minutes is not just adding 's' to the end but almost a different word than singular.

It may seem long but it is very readable I think:

 public static string SpanToReadableTime(TimeSpan span)
    {
        string[] values = new string[4];  //4 slots: days, hours, minutes, seconds
        StringBuilder readableTime = new StringBuilder();

        if (span.Days > 0)
        {
            if (span.Days == 1)
                values[0] = span.Days.ToString() + " dag"; //day
            else
                values[0] = span.Days.ToString() + " dagen";  //days

            readableTime.Append(values[0]);
            readableTime.Append(", ");
        }
        else
            values[0] = String.Empty;


        if (span.Hours > 0)
        {
            if (span.Hours == 1)
                values[1] = span.Hours.ToString() + " uur";  //hour
            else
                values[1] = span.Hours.ToString() + " uren";  //hours

            readableTime.Append(values[1]);
            readableTime.Append(", ");

        }
        else
            values[1] = string.Empty;

        if (span.Minutes > 0)
        {
            if (span.Minutes == 1)
                values[2] = span.Minutes.ToString() + " minuut";  //minute
            else
                values[2] = span.Minutes.ToString() + " minuten";  //minutes

            readableTime.Append(values[2]);
            readableTime.Append(", ");
        }
        else
            values[2] = string.Empty;

        if (span.Seconds > 0)
        {
            if (span.Seconds == 1)
                values[3] = span.Seconds.ToString() + " seconde";  //second
            else
                values[3] = span.Seconds.ToString() + " seconden";  //seconds

            readableTime.Append(values[3]);
        }
        else
            values[3] = string.Empty;


        return readableTime.ToString();
    }//end SpanToReadableTime
Dabriel
  • 403
  • 1
  • 5
  • 12
  • 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. – Neil Oct 23 '15 at 14:57
1

This is a pain in VS 2010, here's my workaround solution.

 public string DurationString
        {
            get 
            {
                if (this.Duration.TotalHours < 24)
                    return new DateTime(this.Duration.Ticks).ToString("HH:mm");
                else //If duration is more than 24 hours
                {
                    double totalminutes = this.Duration.TotalMinutes;
                    double hours = totalminutes / 60;
                    double minutes = this.Duration.TotalMinutes - (Math.Floor(hours) * 60);
                    string result = string.Format("{0}:{1}", Math.Floor(hours).ToString("00"), Math.Floor(minutes).ToString("00"));
                    return result;
                }
            } 
        }
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
rguez06
  • 11
  • 2
1

The Substring method works perfectly when you only want the Hours:Minutes:Seconds. It's simple, clean code and easy to understand.

    var yourTimeSpan = DateTime.Now - DateTime.Now.AddMinutes(-2);

    var formatted = yourTimeSpan.ToString().Substring(0,8);// 00:00:00 

    Console.WriteLine(formatted);
GER
  • 1,870
  • 3
  • 23
  • 30
1

No one has shown approach with decimal format specifier which is my favorite one, especially when used with string interpolation - https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings?redirectedfrom=MSDN#decimal-format-specifier-d

For example:

$"{time.Hours:D2}:{time.Minutes:D2}:{time.Seconds:D2}.{time.Milliseconds:D3}"
// Sample output: 00:00:09.200

You can of course wrap it up in some helper method.

tometchy
  • 609
  • 5
  • 6
0

Here is my version. It shows only as much as necessary, handles pluralization, negatives, and I tried to make it lightweight.

Output Examples

0 seconds
1.404 seconds
1 hour, 14.4 seconds
14 hours, 57 minutes, 22.473 seconds
1 day, 14 hours, 57 minutes, 22.475 seconds

Code

public static class TimeSpanExtensions
{
    public static string ToReadableString(this TimeSpan timeSpan)
    {
        int days = (int)(timeSpan.Ticks / TimeSpan.TicksPerDay);
        long subDayTicks = timeSpan.Ticks % TimeSpan.TicksPerDay;

        bool isNegative = false;
        if (timeSpan.Ticks < 0L)
        {
            isNegative = true;
            days = -days;
            subDayTicks = -subDayTicks;
        }

        int hours = (int)((subDayTicks / TimeSpan.TicksPerHour) % 24L);
        int minutes = (int)((subDayTicks / TimeSpan.TicksPerMinute) % 60L);
        int seconds = (int)((subDayTicks / TimeSpan.TicksPerSecond) % 60L);
        int subSecondTicks = (int)(subDayTicks % TimeSpan.TicksPerSecond);
        double fractionalSeconds = (double)subSecondTicks / TimeSpan.TicksPerSecond;

        var parts = new List<string>(4);

        if (days > 0)
            parts.Add(string.Format("{0} day{1}", days, days == 1 ? null : "s"));
        if (hours > 0)
            parts.Add(string.Format("{0} hour{1}", hours, hours == 1 ? null : "s"));
        if (minutes > 0)
            parts.Add(string.Format("{0} minute{1}", minutes, minutes == 1 ? null : "s"));
        if (fractionalSeconds.Equals(0D))
        {
            switch (seconds)
            {
                case 0:
                    // Only write "0 seconds" if we haven't written anything at all.
                    if (parts.Count == 0)
                        parts.Add("0 seconds");
                    break;

                case 1:
                    parts.Add("1 second");
                    break;

                default:
                    parts.Add(seconds + " seconds");
                    break;
            }
        }
        else
        {
            parts.Add(string.Format("{0}{1:.###} seconds", seconds, fractionalSeconds));
        }

        string resultString = string.Join(", ", parts);
        return isNegative ? "(negative) " + resultString : resultString;
    }
}
JHo
  • 456
  • 4
  • 6
0

If you want the duration format similar to youtube, given the number of seconds

int[] duration = { 0, 4, 40, 59, 60, 61, 400, 4000, 40000, 400000 };
foreach (int d in duration)
{
    Console.WriteLine("{0, 6} -> {1, 10}", d, d > 59 ? TimeSpan.FromSeconds(d).ToString().TrimStart("00:".ToCharArray()) : string.Format("0:{0:00}", d));
}

Output:

     0 ->       0:00
     4 ->       0:04
    40 ->       0:40
    59 ->       0:59
    60 ->       1:00
    61 ->       1:01
   400 ->       6:40
  4000 ->    1:06:40
 40000 ->   11:06:40
400000 -> 4.15:06:40
Rob
  • 26,989
  • 16
  • 82
  • 98
zenny
  • 866
  • 7
  • 11
0

I wanted to return a string such as "1 day 2 hours 3 minutes" and also take into account if for example days or minuttes are 0 and then not showing them. thanks to John Rasch for his answer which mine is barely an extension of

TimeSpan timeLeft = New Timespan(0, 70, 0);
String.Format("{0}{1}{2}{3}{4}{5}",
    Math.Floor(timeLeft.TotalDays) == 0 ? "" : 
    Math.Floor(timeLeft.TotalDays).ToString() + " ",
    Math.Floor(timeLeft.TotalDays) == 0 ? "" : Math.Floor(timeLeft.TotalDays) == 1 ? "day " : "days ",
    timeLeft.Hours == 0 ? "" : timeLeft.Hours.ToString() + " ",
    timeLeft.Hours == 0 ? "" : timeLeft.Hours == 1 ? "hour " : "hours ",
    timeLeft.Minutes == 0 ? "" : timeLeft.Minutes.ToString() + " ",
    timeLeft.Minutes == 0 ? "" : timeLeft.Minutes == 1 ? "minute " : "minutes ");
Piees
  • 75
  • 8