简体   繁体   中英

C# + Format TimeSpan

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?

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.

尝试这个:

Console.WriteLine("{0:D2}:{1:D2}", duration.Minutes, duration.Seconds);

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");

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.

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.

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"));

您可以随时这样做:

string.Format("{0}:{1}", duration.Minutes, duration.Seconds);

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.

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.

TimeSpan t = TimeSpan.Parse("13:45:43");
Console.WriteLine(@"Timespan is {0}", String.Format(@"{0:yy\:MM\:dd\:hh\:mm\:ss}", t));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM