How to format TimeSpan to string before .NET 4.0
Asked Answered
A

2

17

I am compiling in C# using .NET 3.5 and am trying to convert a TimeSpan to a string and format the string. I would like to use

myString = myTimeSpan.ToString("c");

however the TimeSpan.ToString method does not take a format string as an argument until .NET 4.0 and I am using .NET 3.5.

How then would you format a TimeSpan as a string? My final goal is to display the TimeSpan in format hh:mm:ss but am currently receiving hh:mm:ss:fffffff.

I have tried using

myString = string.Format("{0:hh:mm:ss}", myTimeSpan);

but string.Format is only formatting my DateTime and passing different format strings doesn't work when trying to format a TimeSpan.

Already answered 20/7, 2012 at 12:7 Comment(3)
@John: That is not a solution.Benoite
This link might help you: https://mcmap.net/q/129660/-timespan-formatting-duplicateBavardage
https://mcmap.net/q/127375/-how-can-i-string-format-a-timespan-object-with-a-custom-format-in-net Answers your question.Amylene
A
23

One way could be:

TimeSpan ts = DateTime.Now - DateTime.Now.AddHours(-10);
Console.WriteLine(string.Format("{0:00}:{1:00}:{2:00}", ts.TotalHours, ts.Minutes, ts.Seconds));

Result would be something like:

09:59:59

EDIT:

Or you can try:

TimeSpan ts = DateTime.Now - DateTime.Now.AddHours(-10);
DateTime mydate = new DateTime(ts.Ticks);
Console.WriteLine(mydate.ToString(("hh:mm:ss")));

Output would be:

09:59:59
Auberta answered 20/7, 2012 at 12:13 Comment(1)
@Joey, perfect, modified my answerAuberta
C
0

Better is 24*ts.Days+ts.Hours than ts.TotalHours. Compare:

var ts = TimeSpan.FromHours( 23.9 );
Console.WriteLine( ts );
Console.WriteLine( "{0:00}:{1:00}:{2:00}", ts.TotalHours, ts.Minutes, ts.Seconds );
Console.WriteLine( "{0}:{1:00}:{2:00}", ts.TotalHours, ts.Minutes, ts.Seconds );
Console.WriteLine( "{0}:{1:00}:{2:00}", 24*ts.Days+ts.Hours, ts.Minutes, ts.Seconds );
Canikin answered 13/2, 2015 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.