Convert Date String to another Date string with different format

Müsli picture Müsli · Sep 16, 2013 · Viewed 10.4k times · Source

I need to convert an string date with format yyyyMMdd to a date string with format MM/dd/yyyy. Which is the best to do it?

I'm doing this:

DateTime.ParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture).ToString("MM/dd/yyyy")

But I'm not sure, i think there must be a better way. What do you think?

Answer

Habib picture Habib · Sep 16, 2013

What you are doing is fine.

Probably you can improve it by using DateTime.TryParseExact and on successful parsing, format the DateTime object in other format.

string dateString = "20130916";
DateTime parsedDateTime;
string formattedDate;
if(DateTime.TryParseExact(dateString, "yyyyMMdd", 
                    CultureInfo.InvariantCulture, 
                    DateTimeStyles.None, 
                    out parsedDateTime))
{
    formattedDate = parsedDateTime.ToString("MM/dd/yyyy");
}
else
{
       Console.WriteLine("Parsing failed");
}