簡體   English   中英

無法將字符串識別為有效的DateTime(System.FormatException)?

[英]String was not recognized as a valid DateTime(System.FormatException)?

我收到以下錯誤消息:

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);
}

我在textbox上使用CalenderExtender 我嘗試了ParseParseExact ,但是它不起作用。 我在這里做錯了什么?

DateTime Compdate;
if (!String.IsNullOrEmpty(txtRefDate.Text) && DateTime.TryParse(txtRefDate.Text, out Compdate))
{
    obj.RefrenceDate = Compdate.Date;
}

還請看一下TryParseExact() ,它使您可以提供有關輸入的預期格式的更多信息。

如果失敗,則開始記錄失敗的字符串值。 我們需要查看不起作用的示例。

嗯,您似乎在執行許多不必要的步驟來解析和設置DateTime

var textDate = "06-20-2018";

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

    obj.RefrenceDate = parsedDate;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM