42

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

Ex: 20001106

6 Answers 6

58

Use DateTime.ParseExact(). Something like:

   string date = "20100102";
   DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);
Sign up to request clarification or add additional context in comments.

2 Comments

@Dynami try again, I just edited with the proper format (case matters)
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'
11
 DateTime.TryParseExact(myDateString, "yyyyMMdd", 
                         CultureInfo.InvariantCulture, 
                         DateTimeStyles.None, out myDateVar )

1 Comment

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.
4

Check DateTime.ParseExact or DateTime.TryParseExact.

Comments

4

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.

Comments

3
DateTime yourDateTime = DateTime.ParseExact(yourString, "yyyyMMdd", null);

Comments

3

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.