views:

535

answers:

3

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?

+2  A: 

"1999" is not a date, it's a year try 1/1/1999

Steven A. Lowe
Thanks, that is what I thought!
Geo
+8  A: 

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

DateTime.TryParseExact
  ("1999",
   "yyyy",
   CultureInfo.InvariantCulture,
   DateTimeStyles.None,
   out dTransactionDate)
Andrew Hare
It worked. Thanks!!!
Geo
No problem - glad to help!
Andrew Hare
+3  A: 

How about...

DateTime dTransactionDate = new DateTime();
if (DateTime.TryParseExact(sTransactionDate, "yyyy",
    CultureInfo.InvariantCulture, DateTimeStyles.None, out dTransactionDate))
{
    // Happy
}
else
{
    // Sad
}

...or even just...

DateTime dTransactionDate = new DateTime(int.Parse(sTransactionDate), 1, 1);
// Happy
LukeH