68

I am trying to format a TimeSpan element in the format of "[minutes]:[seconds]". In this format, 2 minutes and 8 seconds would look like "02:08". I have tried a variety of options with String.Format and the ToString methods, but I get a FormatException. This is what I'm currently trying:

DateTime startTime = DateTime.Now;
// Do Stuff
TimeSpan duration = DateTime.Now.Subtract(startTime);

Console.WriteLine("[paragraph of information] Total Duration: " + duration.ToString("mm:ss"));

What am I doing wrong? How do I format a TimeSpan element using my desired format?

wonea
  • 4,783
  • 17
  • 86
  • 139
Villager
  • 6,569
  • 22
  • 65
  • 87
  • possible duplicate of [How can I String.Format a TimeSpan object with a custom format in .NET?](http://stackoverflow.com/questions/574881/how-can-i-string-format-a-timespan-object-with-a-custom-format-in-net) – Doctor Jones May 25 '12 at 14:03

11 Answers11

99

NOTE: This answer applies to .NET 4.0 only.

The colon character is a literal and needs to be wrapped in single quotes:

duration.ToString("mm':'ss")

From the MSDN documentation:

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.

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • 2
    Does not work for me ... I think the problem is the TimeSpan, for a DateTime it works – tanascius Mar 16 '10 at 17:10
  • `TimeSpan` doesn't have a `ToString(string)` method. – Joey Mar 16 '10 at 17:13
  • @tanascius, @Johannes Rössel: I just noticed that the `ToString(string)` overload only exists in .NET4. Prior versions of the framework only have the plain `ToString()` method that takes no parameters. – LukeH Mar 16 '10 at 17:35
  • 5
    Is this answer really so bad that it deserves two (so far) downvotes? The OP doesn't specify which version of .NET that they're using, and if their code compiles at all then *they must be using .NET4*. (And their code must be compiling, otherwise how would they be seeing a `FormatException` at runtime?) – LukeH Mar 16 '10 at 17:37
  • 1
    I did not downvote, but you just got my upvote because of your explanation - didn't know that it works in 4.0. By the way: the code compiles in 3.5, too. But the result is wrong ("00:00:00") – tanascius Mar 16 '10 at 23:01
  • 1
    @LukeH It's a good solution in 4.0; down-vote is not appropriate provided the answer is flagged that it applies to 4.0+ (which it is). I added a note the the accepted answer so others can find this solution. It's actually a very good answer given the peculiarities on home `TimeSpan.ToString(...)` works in 4.0. I up-voted this. – Robert Altman May 20 '11 at 00:06
  • This is one of the most frustrating things I've dealt with. `DateTime.ToString()` can be formatted however you want but all of a sudden `TimeSpan` doesn't work the same way? Awesome.... – Brandon Apr 24 '14 at 12:10
  • A good answer that works. But this way of doing things is hardly intuitive. – Steve Smith Sep 16 '22 at 10:52
  • The link is no longer valid. Here is a more recent link. https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings – Kyle Shrader Jan 03 '23 at 16:50
59

Try this:

Console.WriteLine("{0:D2}:{1:D2}", duration.Minutes, duration.Seconds);
Ahmed Abdelkader
  • 1,695
  • 1
  • 13
  • 12
  • oh, you posted while I was writing my answer :) – Joel Mar 16 '10 at 17:13
  • 4
    This isn't really correct, the time separator is a culture sensitive string, available in CultureInfo.DateTimeFormat.TimeSeparator. Or use the DateTime.ToString() method. – Hans Passant Mar 16 '10 at 18:20
  • 1
    @nobugz: Thanks for the valuable info. The OP explicitly requested this specific format. – Ahmed Abdelkader Mar 16 '10 at 21:09
  • 6
    @ahmad: just a heads-up for the untold number of programmers that are going to google this answer some day. – Hans Passant Mar 16 '10 at 21:15
  • @nobugz: Great point. You tought me something big. Thank you. – Ahmed Abdelkader Mar 16 '10 at 21:47
  • 3
    There is another answer here which shows a new ToString() syntax available in .NET 4.0: `duration.ToString("mm':'ss")` (The literal : is quoted inside the format specifier.) Please see answer from @LukeH for more details. – Robert Altman May 19 '11 at 23:56
33

Custom formatting of System.TimeSpan was added in .Net 4, so you can now do the following:

string.Format("{0:mm\\:ss}", myTimeSpan);

(UPDATE) and here is an example using C# 6 string interpolation:

$"{myTimeSpan:hh\\:mm\\:ss}"; //example output 15:36:15

In short you now 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 "." charecters 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
  • 2
    Hard to find the example that did not use .ToString() – Casper Leon Nielsen Apr 14 '13 at 18:54
  • 1
    I wonder which M$ dev in his infinite wisdom thought it was a good idea to have different formatting rules for `DateTime` and `TimeSpan` structs? Especially, if you consider the fact that you get the latter from subtraction of the former. – z33k Sep 17 '21 at 11:13
20

For some mysterious reason TimeSpan never got the ToString() overloads that support formatting until .NET 4.0. For earlier releases, as long as it is positive, you can hijack DateTime.ToString():

TimeSpan ts = new TimeSpan(0, 2, 8);
string s = new DateTime(ts.Ticks).ToString("mm:ss");
wonea
  • 4,783
  • 17
  • 86
  • 139
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
6

The date and time format strings only apply to DateTime and DateTimeOffset. Yo can use a normal format string, though:

string.Format("{0}:{1:00}", Math.Truncate(duration.TotalMinutes), duration.Seconds)

Note that using TotalMinutes here ensures that the result is still correct when it took longer than 60 minutes.

Joey
  • 344,408
  • 85
  • 689
  • 683
3

Try this:

DateTime startTime = DateTime.Now;
// Do Stuff
TimeSpan duration = DateTime.Now.Subtract(startTime);

Console.WriteLine("[paragraph of information] Total Duration: " + duration.Minutes.ToString("00") + ":" + duration.Seconds.ToString("00"));
Sani Huttunen
  • 23,620
  • 6
  • 72
  • 79
3

You can use Format Specifier showcased here -> https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-timespan-format-strings#the-constant-c-format-specifier

It has a constant format specifier with below syntax:

[-][d.]hh:mm:ss[.fffffff] (square brackets are optional)

TimeSpan duration = new TimeSpan(0, 12, 23, 62);
duration.ToString("c");  //Output -> 12:24:02

Hope this helps!!!

Tanmay Sharma
  • 71
  • 1
  • 5
1

You can use the below code.

TimeSpan tSpan = TimeSpan.FromSeconds(allTotalInMinutes);
string tTime = string.Format("{1:D2}:{2:D2}", tSpan.Minutes, tSpan.Seconds);

It will show ie 34:45 format.

Hope it will help you.

SysDragon
  • 9,692
  • 15
  • 60
  • 89
0

you could always do:

string.Format("{0}:{1}", duration.Minutes, duration.Seconds);
Joel
  • 16,474
  • 17
  • 72
  • 93
  • 1
    With an empty format string that'd be a nice, empty result ;-) – Joey Mar 16 '10 at 17:14
  • @Joel: And you don't even bother to edit your answer and correct it? Wow you're brave! ;) – Robert Koritnik Mar 30 '11 at 16:36
  • 1
    @Robert Koritnik: You realize that this answer is over a year old, right? I guess I'll edit it for your benefit so you don't have to scroll up and see better solutions. – Joel Mar 30 '11 at 21:31
  • 1
    @Joel: it was just an observation after a year. @Joey told you about the problem on the same day you answered. I was astonished by that not that nobody told you or that you didn't see it. Never mind. – Robert Koritnik Mar 31 '11 at 06:52
  • Yeah, I don't know why I didn't bother to fix it when I made that edit. I was just confused why someone would bring it up after a year. – Joel Mar 31 '11 at 15:38
0

Based on this MSDN page describing the ToString method of TimeSpan, I'm somewhat surprised that you can even compile the code above. TimeSpan doesn't have a ToString() overload that accepts only one string.

The article also shows a function you can coyp and use for formatting a TimeSpan.

John Fisher
  • 22,355
  • 2
  • 39
  • 64
  • The code will compile if the OP is using .NET4, but will then hit a runtime `FormatException` as they describe. – LukeH Mar 16 '10 at 17:31
-2
TimeSpan t = TimeSpan.Parse("13:45:43");
Console.WriteLine(@"Timespan is {0}", String.Format(@"{0:yy\:MM\:dd\:hh\:mm\:ss}", t));
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Rob
  • 855
  • 7
  • 8
  • -1: Your code throws `FormatException`, as there is no concept of years or months in a `TimeSpan`. Also, the call to `String.Format` is unnecessary as `Console.WriteLine` supports Composite Formatting. [MSDN: custom TimeSpan format](https://msdn.microsoft.com/en-us/library/ee372287%28v=vs.110%29.aspx). – Nigel Touch Jan 29 '15 at 14:53