[英]Valid Date Time conversion from String
我不斷收到錯誤消息“該字符串未被識別為有效的 DateTime。有一個從索引 0 開始的未知單詞。” 但我不確定原因。
//Date and Age
String months = Convert.ToString(txtMonth);
String days = Convert.ToString(txtDay);
String year = Convert.ToString(txtYear);
String DOB = days + " " + months + " " + year;
int age = AgeCalc(DOB);
//Age Function
private int AgeCalc(string date)
{
DateTime DOB = Convert.ToDateTime(date);
DateTime Year = DateTime.Now;
TimeSpan span = Year - DOB;
DateTime Age = DateTime.MinValue.AddDays(span.Days);
return Age.Year - 1;
}
//Separate Box
MessageBox.Show("First Name:" + fName + "\nLast Name:" + lName + "\nGender:" + gender + "\nAge:" +
age + "\nHeight (in inches):" + height + "\nWeight (lbs):" + weight + "\nMax Heart Rate:" + heartRate +
"\nTarget Heart Rate:" + targetRate + "\nBMI:" + BMI, "Result");
應要求提供更多代碼。
假設您只允許用戶輸入正確的值(有效整數)。 你可以用這個
new DateTime(Convert.ToInt32(txtYear), Convert.ToInt32(txtMonth), Convert.ToInt32(txtDay));
如果你想檢測用戶是否輸入了錯誤的值,試試這個
string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy","dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy"};
if (DateTime.TryParseExact(date, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime DOB))
{
// DOB variable is ready to use
Label1.Text = DOB.ToShortDateString();
} else {
//error handling goes here
Label1.Text = "ERROR: Invalid value";
}
DOB.ToShortDateString() 將轉換回字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.