-1

I'm new to c# how can I convert my input string in to DateTime.

_toDate = 5/22/2015

I cannt use

DateTime.ParseExact(_toDate, "yyyy-MM-dd", null);

Or

Convert.ToDateTime(_toDate)

throw an exception String was not recognized as a valid DateTime.

Note : String shold be excact the same as above.

Appreciate your reply

leppie
  • 115,091
  • 17
  • 196
  • 297
  • 3
    `yyyy-MM-dd` does not seem to match your date. – Magnus Aug 03 '15 at 12:57
  • possible duplicate of [String was not recognized as a valid DateTime " format dd/MM/yyyy"](http://stackoverflow.com/questions/2193012/string-was-not-recognized-as-a-valid-datetime-format-dd-mm-yyyy) – Ian Ringrose Aug 03 '15 at 13:07

1 Answers1

9

Clearly, your string and format does not match.

From documentation;

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

You need to use M/dd/yyyy with a culture that has / as a DateSeparator like InvariantCulture .

string _toDate = "5/22/2015";
DateTime myDate = DateTime.ParseExact(_toDate, "M/dd/yyyy", CultureInfo.InvariantCulture);

When you use null as an IFormatProvider, it's threaded as your CurrentCulture and if your CurrentCulture doesn't have / as a DateSeparator, you will get FormatException because / custom format specifier has a special meaning as replace me with current culture or supplied culture date separator.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • @Downvoter care to comment at least so I can see where I _might_ be wrong? – Soner Gönül Aug 03 '15 at 13:39
  • That works for the specific case given, but it's more likely the OP needs to use `M/d/yyyy`. It's unlikely the format being used would zero pad the day, but not the month. Also I'm not the down voter. – juharr Aug 03 '15 at 14:04
  • @juharr That works for the specific case because it is the _only_ case we have. You have a point, `d` specifier parses it as well but since OP try to parse it with `dd` specifier, there is a chance that single day numbers _may_ have leading zeros. – Soner Gönül Aug 03 '15 at 17:27