Question

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?

Was it helpful?

Solution

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

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

OTHER TIPS

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

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

Also verify on a system calendar that the date you are attempting to parse existed. Just like you'll find "2/29/1949" is also going to return false because it never existed on the calendar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top