cfbd
cfbd

Reputation: 1130

DateTime ParseExact exception

var str = "00:00:00 02/01/1990";
var dt = DateTime.ParseExact(str, "hh:mm:ss dd/MM/yyyy", null);

The above code is throwing an exception "String was not recognized as a valid DateTime."

I thought using ParseExact and specifying the exact format this would be okay. What is wrong with the above?

EDIT:

Solved using invariant culture. Thanks for comments.

var dt = DateTime.ParseExact(str, "HH:mm:ss dd/MM/yyyy", CultureInfo.InvariantCulture);

Upvotes: 3

Views: 484

Answers (2)

Furqan Safdar
Furqan Safdar

Reputation: 16698

Yes usually in DateTime format the Date comes first before Time. Try this out:

var str = "02/01/1990 00:00:00";
var dt = DateTime.ParseExact(str, "hh:mm:ss dd/MM/yyyy", null);

EDITED: OK so you do one trick to get it done:

var str = "00:00:00 02/01/1990";
var split = str.Split(new char[] { ' ' });
if (split.Length == 2)
    str = String.Format("{0} {1}", split[1], split[0]);
var dt = DateTime.ParseExact(str, "hh:mm:ss dd/MM/yyyy", null);

Upvotes: 1

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

The "hh" format specifier is for 12-hour AM/PM time, which doesn't support a "00". Try defining it in 24-hour time: HH:mm:ss dd/MM/yyyy

Upvotes: 1

Related Questions