0

That question may be already been answered here, but I could not find any answers. I'm trying to to convert the string 25APR18 to 2018-04-25.

I tried to do the following:

DateTime.ParseExact("25APR18", "yyyy-mm-dd", CultureInfo.InvariantCulture);

But it does not convert and gives me the error saying "String was not recognized as a valid DateTime."

I was not able to find the right solution.

Any suggestions?

12
  • 2
    There are a lot of answers, all of which show how to use DateTime.ParseExact. There are no dashes in this string, so why use yyyy-mm-dd? Commented May 7, 2018 at 14:28
  • I will look into that as well. Thx
    – gene
    Commented May 7, 2018 at 14:28
  • 3
    Does 25APR18 look like it's in the format yyyy-MM-dd? Commented May 7, 2018 at 14:30
  • 6
    It's fascinating how many uses ParseExact without understanding the nature of the word Exact. The right format for that date string would be "ddMMMyy", tested and works. Commented May 7, 2018 at 14:30
  • 1
    DateTime don't store display format. Only string representations of datetime have a display format. So when using DateTime.ParseExact, the format you specify is the display format of the string you want to parse. Commented May 7, 2018 at 14:31

2 Answers 2

6

You can use:

DateTime date = DateTime.ParseExact("25APR18", "ddMMMyy", CultureInfo.InvariantCulture);

The string format is case sensitive representing the input format you want to match. Lower case mm represents minutes but you need month abbreviated name MMM and that's one issue with the code you posted. Full list of format specifiers can be found here.

Once you have a DateTime object you can retrieve the date as string with new format:

string formattedDate = date.ToString("yyyy-MM-dd");

Which produces:

2018-04-25

7
  • I tried that option already. It gives me the same error that the string cannot be recognized as valid DateTime
    – gene
    Commented May 7, 2018 at 14:35
  • 2
    While the code is probably correct, this answers lacks explanations. It's no more then a simple code dump. Please try to elaborate on what's the reason this code is correct while the code in the question is wrong. Commented May 7, 2018 at 14:36
  • 1
    @gene No it didn't give you that error. Commented May 7, 2018 at 14:36
  • 1
    @gene that is incorrect. It converts to a DateTime object. A DateTime object stores the datetime as a number and thus has no human-readable representation. See my answer here for a better explanation. Commented May 7, 2018 at 14:40
  • 1
    That's better. Now I can upvote your answer. Commented May 7, 2018 at 14:42
0

Your date parse code should be

DateTime.ParseExact("25APR18", "ddMMMyy", CultureInfo.InvariantCulture);

Not the answer you're looking for? Browse other questions tagged or ask your own question.