C# – Why DateTime.TryParse returning false when given a real year string

.netc++datetimetryparse

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?

Best Solution

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

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