0

Possible Duplicate:
DateTime.ParseExact string format exception

FormatException was found !

I tried to convert a string to DateTime.

string dateString1 = "5/22/1985 12:00:00 AM";

DateTime myDate = 
    DateTime.ParseExact(dateString1, 
                        "mm-dd-yyyy",
                        System.Globalization.CultureInfo.InvariantCulture);

It gives me an error, but when I try to convert a string in this format

string dateString2 = "10-10-2000";

This second string is working just fine but the dateString1 does not work!

Community
  • 1
  • 1
xargs
  • 2,741
  • 2
  • 21
  • 33
  • 1
    I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Jan 23 '13 at 20:09
  • 2
    http://stackoverflow.com/questions/2000580/datetime-parseexact-string-format-exception – MUG4N Jan 23 '13 at 20:10
  • 2
    "mm" in `DateTime` format strings means **minutes**, not months. – Dour High Arch Jan 23 '13 at 20:14

4 Answers4

6

Your code answers your question. You're using ParseExact, which was given a format that won't accept your first string.

From the MSDN (http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx):

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

CassOnMars
  • 6,153
  • 2
  • 32
  • 47
1

Try this:

DateTime myDate = DateTime.ParseExact(dateString1, "M/d/yyyy h:m:s tt", System.Globalization.CultureInfo.InvariantCulture);
kopaty4
  • 2,236
  • 4
  • 26
  • 39
0

You're specifically making your code parse the date exactly according to the format "mm-dd-yyyy", so of course only a date with that format will work. If you use DateTime.Parse instead, both examples will work.

Yandros
  • 722
  • 1
  • 8
  • 16
  • Thanks ! I realize that now , thanks for the tips. It is the first time I use DateTime, I'm stil learning :) – xargs Jan 23 '13 at 20:37
0

You could use Parse instead of ParseExact:

DateTime myDate = DateTime.Parse(dateString1);

This should correctly parse either of your two examples. http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

chris_dotnet
  • 844
  • 9
  • 14