Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why has this particular TimeSpan format string stopped working in .NET 4?

Consider this code (prestuffed with an example):

DateTime dt1 = DateTime.Parse("7/30/2010 9:33:29.1234567 AM");
DateTime dt2 = DateTime.Parse("6/30/2010 9:33:00.7654321 AM");

TimeSpan ts = dt1 - dt2;

Console.WriteLine(string.Format( "{0:d.hh:mm:ss.ff}", ts ));

This is representative of a piece of code that I've had working since .NET 1.1 at least.

It worked fine in 1.1 through 3.5 with the following output (for these dummied up inputs):

30.00:00:28.3580246

But now I'm seeing that it dies in .NET 4 with the error message:

Input string was not in a correct format.

So it's as if .NET 4 has suddenly decided it doesn't like this format for time differences. Changing the line to, say

Console.WriteLine(string.Format( "{0}", ts.ToString("d.hh:mm:ss.ff") ));

has the same effect.

Now the thing I've noticed is that if I just do the default .ToString() I get the same output. I believe the thought process was that this was an insurance policy against the default format changing in a future version. But now it doesn't look like that's even an option.

Does anyone know why this changed and if I'm doing something wrong or if there's a best practices way to do what I'm trying to accomplish?

like image 547
Tom Kidd Avatar asked Jul 30 '10 15:07

Tom Kidd


People also ask

What is the format of TimeSpan in C#?

You can format a TimeSpan in the hh: mm: ss format in C#.

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.


2 Answers

There is a configuration switch to restore the old behaviour of TimeSpan.

like image 55
Mitch Wheat Avatar answered Oct 15 '22 17:10

Mitch Wheat


An alternative to the configuration switch is a format change that is compatible with previous versions.

Console.WriteLine(string.Format( "{0:hh\\:mm\\:ss.ff}", ts )); 

This solution is detail here.

like image 32
wilk Avatar answered Oct 15 '22 18:10

wilk