Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format TimeSpan to string before .NET 4.0

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.

like image 888
Ishkur Avatar asked Jul 20 '12 12:07

Ishkur


People also ask

What is the format of a TimeSpan?

"c" is the default TimeSpan format string; the TimeSpan. ToString() method formats a time interval value by using the "c" format string. TimeSpan also supports the "t" and "T" standard format strings, which are identical in behavior to the "c" standard format string.

How do I format a string to mm dd yyyy?

string dateString = int. Parse("20120321"). ToString("yyyy/MM/dd");


1 Answers

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
like image 190
Habib Avatar answered Sep 30 '22 18:09

Habib