What is the best way to convert string to date in C# if my incoming date format is in YYYYMMDD
Ex: 20001106
What is the best way to convert string to date in C# if my incoming date format is in YYYYMMDD
Ex: 20001106
DateTime.TryParseExact(myDateString, "yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out myDateVar )
Use DateTime.ParseExact(). Something like:
string date = "20100102";
DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);
DateTime yourDateTime = DateTime.ParseExact(yourString, "yyyyMMdd", null);
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.
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());
}