Question

How do I convert a date string, in the general form of "ccyymmdd" in to a DateTime object in C#?

For example, how would I convert "20100715" in to a DateTime object.

Please - No RTFM links to Microsoft Tech Docs.

Many Thanks...

Was it helpful?

Solution

using System.Globalization;

DateTime.ParseExact("20100715", "yyyyMMdd", CultureInfo.InvariantCulture);

OTHER TIPS

var dt = DateTime.Parse("your date string").ToString("yymmdd");

I don't think cc is a valid date formatting option?

As Richard points out, you can also use DateTime.ParseExact which allows you to use culture information for the parsing, or you can use DateTime.TryParseExact which is the same as DateTime.ParseExact, but if there is an exception then a null date is returned rather then an exception being raised.

EDIT:

The question has been updated so that a DateTime is specifically returned. In that case you can omit the .ToString() part of my answer. Calling DateTime.Parse() will return a DateTime object. When getting the date value via ToString(), simply pass the required formatting string to get the date in the desired format. Cheers. Jas.

Take a look at this and this

DateTime.Parse();
DateTime.ParseExact();

And worth a mention

DateTime.TryParse();

If your date string is already sanitized (Borrowed from Mike's answer):

DateTime dt = DateTime.ParseExact("20100715", "yyyyMMdd", CultureInfo.InvariantCulture);

Otherwise:

DateTime dt;
if (!DateTime.TryParseExact("20100715", "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
    // Handle bad date
}

System.DateTime.Parse(yourDateString)

You might have to manipulate your string to a format that the method can handle first.

See http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

for more info

I'm not sure what the "cc" part is, but there are a few options.

DateTime.Parse(string) may be able to convert the string, but if the string is in a non-standard format you may have to do some pre-conversion first.

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