-5

Possible Duplicate:
String was not recognized as a valid DateTime ParseExact

I have a datetime string input to my application, the value is

11/22/2011 12:00:00 AM

when i call Convert.ChangeType(abovedate,typeof(DateTime));

I get a Formatexception, is there a way like a regex to find the format of the datetime and then create a dateformat and then apply so that i get back the correct datetime after parsing the string back to DateTime.

Community
  • 1
  • 1
Saravanan
  • 7,637
  • 5
  • 41
  • 72
  • 1
    asked and answered trillions of times here in StackOverflow: http://stackoverflow.com/questions/2186861/string-was-not-recognized-as-a-valid-datetime-parseexact – Davide Piras Dec 13 '11 at 13:59
  • For example, http://stackoverflow.com/questions/1277320/datetime-string-parsing – gimel Dec 13 '11 at 14:02
  • Further to the answers below (+1 btw) you may wish to take into account the culture sensitive nature of date format i.e. your example is US format, which would be incorrect for Europe – ChrisBD Dec 13 '11 at 14:05
  • @liho1eye: That's cheating the banning of *lmgtfy* links in comments ;) – Otiel Dec 13 '11 at 14:19
  • @Otiel I had no idea it is banned. I shortened it because it is prettier that way. – Ilia G Dec 13 '11 at 14:35
  • closing this as exact duplicate is absolutely ridiculous.. some users have understood the question and others have just given some namesake replies and url references.. – Saravanan Dec 14 '11 at 03:34

5 Answers5

4

I believe what you need is DateTime.Parse: http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
Gigi
  • 28,163
  • 29
  • 106
  • 188
1

What about using DateTime.Parse Method http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

JonH
  • 32,732
  • 12
  • 87
  • 145
  • I wanted to find the format in the string and then apply that as a format so that i can getback the datetime object without `FormatException`. – Saravanan Dec 13 '11 at 14:01
1

The method you're after is DateTime.TryParseExact: http://msdn.microsoft.com/en-us/library/ms131044.aspx

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

You can try to use DateTime.Parse method or DateTime.ParseExact

Alexander Yezutov
  • 3,144
  • 2
  • 21
  • 23
0

Your string looks fine. However, you can use TryParse, and then if it's successful (true), pass the parsed variable to a dateTime var.

DateTime dateTime; if(!DateTime.TryParse(dateTimeToValidate, out dateTime))

Michael C. Gates
  • 982
  • 1
  • 6
  • 18