Geo Geo - 2 months ago 10
C# Question

Why DateTime.TryParse returning false when given a real year string?

In the code below I am giving the function a sTransactionDate="1999" and I am trying to covert it to a date x/x/1999.

DateTime dTransactionDate = new DateTime();
if(DateTime.TryParse(sTransactionDate, out dTransactionDate))
{ //Happy
}else
{ //Sad
}


if the string is "1999" it will always end up in sad. Any ideas?

Answer

Try something like this (adjust the CultureInfo and DateTimeStyles appropriately):

DateTime.TryParseExact
  ("1999",
   "yyyy",
   CultureInfo.InvariantCulture,
   DateTimeStyles.None,
   out dTransactionDate)
Comments