2

Rephrasing the question found at SO.

Code 1 :

DateTime.TryParse("5-5-5-5" , CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal  , out result);

Code 2:

DateTime.TryParse("5-5-5-5.00" , CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal  , out result);

When the format is changed to 5-5-5-5.00 entire result changes ,Why does that happen ?Does that depend on Culture properties ?

Community
  • 1
  • 1
Tharif
  • 13,794
  • 9
  • 55
  • 77
  • 1
    You look like you have a non-standard time format in the first place. Perhaps you might want to use `TryParseExact` and specify what you are expecting the string to be precisely to avoid the code having to guess at your format - that guess being what is changing between the different lines of code. – Chris Jun 30 '15 at 12:25
  • @Chris let me check TryParseExact result – Tharif Jun 30 '15 at 12:28
  • Seems for me that it's trying to make a decent stab at the first one and getting _some_ datetime out of it, but completely failing to see any valid format whatsoever in the second so returning DateTime.MinValue instead – James Thorpe Jun 30 '15 at 12:29
  • Indeed, jsut added an answer to that effect. Not checking the return value of `DateTime.TryParse` is the error here. – Chris Jun 30 '15 at 12:30
  • 1
    I'm a human and I don't know how to interpret those. How would you expect a computer to do any better? – Rik Jun 30 '15 at 12:41

2 Answers2

1

The problem here is that in the first case it makes a guess as to what you mean and gives you a date. In the second case it cannot work out what you are meaning and so fails to parse. Luckily TryParse has a mechanism for reporting whether it succeeded or not, its return value. While the first returns true the second returns false and thus the value of result is meaningless and shouldn't be examined (though it seems is default(DateTime)).

As I mentioned in comments when using unusual formats for your DateTime strings it is usually best to use DateTime.TryParseExact. This works very similarly except that you tell it exactly what format you expect the string to be in and it uses that to parse rather than trying its best guess of what you mean. You will still need to check the return value in case the input was in the wrong format (or you got your format specifier wrong).

Chris
  • 27,210
  • 6
  • 71
  • 92
1

Do like in this answer

But they tell system what the string is: "5-5-5-5" is a horrible string format for a date. The format string would proberbly be: "d-M-y-h" in your case unless i misunderstand

Community
  • 1
  • 1