3
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);
2
  • what framework version were you targeting? Seems to work for 4.0 Commented Oct 27, 2012 at 7:59
  • The : and / characters are substituted by the time and date separation characters for the local culture, even for ParseExact(). You thus must specify a culture to get reproducible results, like invariant. Commented Oct 27, 2012 at 13:34

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I get the same error with HH, "String was not recognized as a valid DateTime."
1

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

1 Comment

The program is importing data from a csv file. In the csv file the format is "00:00:00 02/01/1990" rather than "02/01/1990 00:00:00". Which is why I need to use the format specified above.

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.