tags:

views:

452

answers:

6

What is the best way to convert string to date in C# if my incoming date format is in YYYYMMDD

Ex: 20001106

+5  A: 
 DateTime.TryParseExact(myDateString, "yyyyMMdd", 
                         CultureInfo.InvariantCulture, 
                         DateTimeStyles.None, out myDateVar )
womp
I used this method since it allowed me to check the return value of TryParseExact and know if the date converted properly. I set a default when it did not.
Randy Eppinger
+5  A: 

Check DateTime.ParseExact or DateTime.TryParseExact.

Fernando
+17  A: 

Use DateTime.ParseExact(). Something like:

   string date = "20100102";
   DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);
Brandon
@Dynami try again, I just edited with the proper format (case matters)
Ahmad Mageed
As per Luke's solution it works fine date format should be 'yyyyMMdd' else is thowing expection 'string was not recognized as a valid datetime'
Nev_Rahd
+2  A: 
DateTime yourDateTime = DateTime.ParseExact(yourString, "yyyyMMdd", null);
LukeH
+2  A: 

use DateTime.TryParseExact with a pattern string of "yyyyMMdd" if you are on .NET 2.0 or better.

If you are stuck with .NET 1.1 use DateTime.ParseExact

see Standard DateTime Format Strings for the rules for making pattern strings.

John Knoeller
A: 

Using TryParseExact is generally nicer than ParseExact as it won't throw an exception if the conversion fails. Instead it returns true if it's successful, false if it's not:

DateTime dt;
if (DateTime.TryParseExact("20100202", "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
   Console.WriteLine(dt.ToString());
}
Steve Wortham