Z.V
Z.V

Reputation: 1471

Handle inconsistent date format string conversion to DateTime

Would like to make a conversion to DateTime from the following strings of datetime format:

"3/20/2017 4:03:03 PM"
"03/20/2017 4:03:03 PM"
"3/20/2017 04:03:03 PM"
"03/20/2017 04:03:03 PM"
etc

Been using try DateTime.ParseExact with the format "MM/dd/yyyy hh:mm:ss tt" but Format Exception is caught, Is there a better way to do this?

Upvotes: 0

Views: 287

Answers (2)

Sadique
Sadique

Reputation: 22841

You can parse dates passing all custom Formats in an array:

string[] strDates = new string[]{"3/20/2017 4:03:03 PM"
                    ,"03/20/2017 4:03:03 PM"
                    ,"3/20/2017 04:03:03 PM"
                    ,"03/20/2017 04:03:03 PM"};

DateTime dt = DateTime.Now;
string[] strFormats = new string[] { "M/dd/yyyy h:mm:ss tt", "dd/MMM/yyyy h:mm:ss tt","MM/dd/yyyy h:mm:ss tt" };
foreach (var item in strDates)
{
    foreach (var format in strFormats)
    {
        dt = DateTime.ParseExact(item, format, CultureInfo.InvariantCulture);
    }
}

Or pass the array directly:

dt = DateTime.ParseExact(item, strFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);

Upvotes: 2

Thiyagu Rajendran
Thiyagu Rajendran

Reputation: 655

Try this, it will work

string dateString, format;  
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "3/20/2017 4:03:03 PM";
format = "M/dd/yyyy h:mm:ss tt";

  try {
     result = DateTime.ParseExact(dateString, format, provider);
     Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
  }
  catch (FormatException) {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }

Upvotes: 0

Related Questions