2

I'm trying to convert a date string in one format into another. However, I get this exception error message

String was not recognized as a valid DateTime.

My code is as follows:

string theDate = "28-Feb-13 4:00:00 PM";

DateTime tempDate = DateTime.ParseExact(theDate, "dd-MMM-yy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None);

convertedDate = tempDate.ToString("yyyy/MM/dd hh:mm:ss");

I seriously have no idea what went wrong.

1
  • 2
    I think your issue is string to datetime and not the other way around as in the title Commented Feb 15, 2013 at 7:36

1 Answer 1

13

You must change

28-Feb-13 4:00:00 PM to 28-Feb-13 04:00:00 PM

or

dd-MMM-yy hh:mm:ss tt to dd-MMM-yy h:mm:ss tt

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

9 Comments

When DateTime says ParseExact, it means it.
So that was what it was all about! And here I thought that the computer is smart enough to detect that. Thank you for your help. I really appreciate it after I've been staring at the code for some time
@SWeko : I should have suspected that it took the word 'Exact' seriously :D
@ixora DateTime.Parse is the smart one that tries to figure out what kind of date string you have, tries to help out, and often goes horribly wrong. Using ParseExact is telling the compiler "I know my data better than you. Work like this and do not try to second guess me".
@ixora No, convertedDate is correct and follows the specified format. If you think it's wrong, that's because the format specified is wrong. See here how to define the correct format: msdn.microsoft.com/en-us/library/8kb3ddd4.aspx Or maybe you're referring to yyyy/MM... being output as yyyy-MM...?
|

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.