无法将字符串识别为有效的DateTime(System.FormatException)?

时间:2018-06-20 13:22:52

标签: c#

我收到以下错误消息:

  

mscorlib.dll中发生了'System.FormatException'类型的异常   但未在用户代码中处理

     

其他信息:无法将字符串识别为有效的DateTime。

这是我的代码:

if (txtRefDate.Text != "")
{
    string[] splitdate = txtRefDate.Text.Split('-');
    string newdate = splitdate[1] + "-" + splitdate[0] + "-" + splitdate[2];
    DateTime Compdate = Convert.ToDateTime(newdate);//On this line i'm getting error
    string date = Compdate.ToString("yyyy-MM-dd");
    obj.RefrenceDate = Convert.ToDateTime(date);
}

我在CalenderExtender上使用textbox。我尝试了ParseParseExact,但是它不起作用。 我在这里做什么错了?

2 个答案:

答案 0 :(得分:7)

Arrays.equals

还可以查看equals,它可以让您提供有关输入的预期格式的更多信息。

如果失败,则开始记录失败的字符串值。我们需要查看无效的示例。

答案 1 :(得分:1)

嗯,您似乎在执行许多不必要的步骤来解析和设置DateTime

var textDate = "06-20-2018";

if (!string.IsNullOrEmpty(textDate))
{
    var parsedDate = DateTime.ParseExact(textDate, "MM-dd-yyyy", null);

    obj.RefrenceDate = parsedDate;
}