[英]C# Cannot implicitly convert type 'string' to 'System.DateTime'
[英]Cannot implicitly convert type bool to System.DateTime (C#)
我正在嘗試convert
string to datetime to validate
convert
string to datetime to validate
用戶輸入是否實際上是一個日期。
我得到的錯誤是:
Cannot implicitly convert type bool to System.DateTime.
我已經在網上尋找了一段時間,找不到足夠具體的信息來幫助我理解。
碼:
public bool is21YearsOfAge(string argument) { DateTime _parsedDateArgument; DateTime convertStringToDate = System.DateTime.TryParse(argument, out >_parsedDateArgument); if (convertStringToDate > DateTime.Now) { //do something } }
提前致謝。
DateTime.TryParse返回bool以指示解析是否成功。 所以你應該做
System.DateTime.TryParse(argument, out _parsedDateArgument);
DateTime convertStringToDate =_parsedDateArgument
它應該是
DateTime convertStringToDate;
if(System.DateTime.TryParse(argument, out convertStringToDate))
{
//Now you will have converted date in convertStringToDate
if (convertStringToDate > DateTime.Now)
{
//do something
}
}
else
{
//argument not have a valid date
}
如果參數將要轉換的有效日期字符串,則System.DateTime.TryParse將重新運行true。 並且轉換后的日期將存儲在其out參數中。
查看DateTime.TryParse
的文檔 -它返回一個bool
,但是具有用於解析結果的out參數:
DateTime dateTime;
bool success = DateTime.TryParse(text, out dateTime);
如果success
為假,則表示文本無法解析。 (因此通常在這一點上,您會向用戶顯示錯誤。)
您已經有了out
參數-為什么期望最后得到兩個不同的DateTime
值(一個作為返回值,一個來自out
參數)?
當您遇到這樣的錯誤時,請始終閱讀文檔,作為診斷問題的第一步。
DateTime.TryParse不返回DateTime值。 它返回一個布爾值,指示是否可以解析它。
改為使用
DateTime convertStringToDate;
if(DateTime.TryParse(argument, out convertStringToDate)){
//ok value is good
}else{
//Not ok value is not good
}
用這個代替
DateTime _parsedDateArgument;
bool success = System.DateTime.TryParse(argument, out _parsedDateArgument);
永遠記住, Tryparse
總是返回布爾值。
TryParse返回bool
,僅使用Parse
,或將out變量分配給您擁有的新變量:
System.DateTime.TryParse(argument, out _parsedDateArgument);
DateTime convertStringToDate = _parsedDateArgument;
或像這樣:
DateTime convertStringToDate = DateTime.Parse(argument);
添加以下名稱空間
using System.Globalization;
創建CultureInfo類的對象
CultureInfo MyCI = new CultureInfo("en-US");
DateTime convertStringToDate = System.DateTime.TryParse(argument.ToString("MM/dd/yy", MyCI), out _parsedDateArgument);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.