9

I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?

JoshL
  • 10,737
  • 11
  • 55
  • 61

6 Answers6

30
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);

or

DateTime result;
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);

More info in the MSDN documentation on ParseExact and TryParseExact.

Kols
  • 3,641
  • 2
  • 34
  • 42
Paul van Brenk
  • 7,450
  • 2
  • 33
  • 38
4

DateTime.TryParse method

Steven A. Lowe
  • 60,273
  • 18
  • 132
  • 202
  • Since I can't edit your answer, I thought it might help to provide a link to the MSDN article for that method. http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx – Sean Hanley Sep 23 '08 at 19:39
  • [@Yadyn]: i figured the intellisense would be enough, but ok i added the link to be thorough - thanks! – Steven A. Lowe Sep 25 '08 at 18:38
4

you could try also TryParseExact for set exact format. method, here's documentation: http://msdn.microsoft.com/en-us/library/ms131044.aspx

e.g.

DateTime outDt;
bool blnYYYMMDD = 
     DateTime.TryParseExact(yourString,"yyyyMMdd"
                            ,CultureInfo.CurrentCulture,DateTimeStyles.None
                            , out outDt);

I hope i help you.

stefano m
  • 4,094
  • 5
  • 28
  • 27
  • Dude! That is so useful, I lost nearly an hour over this, even though I know I've done it before somewhere. – NeedHack Mar 31 '09 at 08:46
0

You can also do Convert.ToDateTime

not sure the advantages of either

Sara Chipps
  • 9,322
  • 11
  • 58
  • 103
0

Using TryParse will not throw an exception if it fails. Also, TryParse will return True/False, indicating the success of the conversion.

Regards...

Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
0

You can use the TryParse method to check validity and parse at same time.

DateTime output;
string input = "09/23/2008";
if (DateTime.TryParseExact(input,"MM/dd/yy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output) || DateTime.TryParseExact(input,"yyyyMMdd", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output))
{
    //handle valid date
}
else
{
    //handle invalid date
}
Skippy
  • 145
  • 2
  • 9