Search code examples
c#exceptionformatexception

Why is this throwing System.FormatException:String was not recognized as a valid DateTime


Why does this:

Convert.ToDateTime("08/31/2017")

throw an System.FormatException but not this:

Convert.ToDateTime("09/12/2017")

If you need more information please ask and I will update or comment. I have no clue what is causing this issue, so I don't know what details you need.


Solution

  • The default order for this date format on your computers culture is Day/Month/Year, as 31 is not a valid month it fails. If you want this order, you need to provide the format with it:

    var x = DateTime.ParseExact("08/31/2017", "MM/dd/yyyy",CultureInfo.InvariantCulture);