Why did this particular TimeSpan format string stop working in .NET 4?

Consider this code (exceeded by 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 part of the code that I have been working with .NET 1.1 at least.

It worked perfectly in versions 1.1 through 3.5 with the following output (for these nested inputs):

30.00:00:28.3580246

But now I see that he is dying in .NET 4 with an error message:

Input string was not in a correct format.

So, as if .NET 4 had suddenly decided that this format is not suitable for time differences. Change the line let's say

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

has the same effect.

Now I noticed that if I just do the default .ToString(), I get the same result. I believe that the thought process was that it was an insurance policy against changing the default format in a future version. But now it doesn’t even seem like an option.

- , , - , ?

+5
5
+6

, .

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

.

+3

, , , , TimeSpan (.NET < 4.0).

. TimeSpan 30.00:00:28.3580246 .

MSDN:

.NET Framework TimeSpan IFormattable .

, TimeSpan , String.Format. , IFormattable , FormatException. , TimeSpan IFormattable, TimeSpan.ToString(). , , , FormatException.

+1

Mitch Wheat Saeb Amini , , TimeSpan IFormattable .NET 4.0. , TimeSpan.ToString(), .

, TimeSpan IFormattable, TimeSpan.ToString. , , , FormatException.

, TimeSpan .NET Framework, TimeSpan DateTime, , :

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}", new DateTime(ts.Ticks))) 
// prints 30.00:00:28.36
+1

I pasted your code snippet and there seems to be a culture problem:

with .NET 2 exception FormatException also

If I specified a us culture (the default culture is fr-FR), the code works:

DateTime dt1 = DateTime.Parse("7/30/2010 9:33:29.1234567 AM", CultureInfo.GetCultureInfo("en-US"));

You can also specify an invariant culture to ignore the culture

DateTime dt1 = DateTime.Parse("7/30/2010 9:33:29.1234567 AM", CultureInfo.InvariantCulture);
0
source

All Articles