该字符串未被识别为有效的 DateTime."

我觉得我的日期格式已经设置正确了呀 而且转换过来也没错啊
2025-03-10 22:42:25
推荐回答(5个)
回答1:

ParseExact是严格匹配,borrowtime必须是2014/01/02格式,你错误原因可能有3:
1. 年月日格式错误,如2014-01-02是错误;
2. 包含了时间格式,如2014/01/02 10:00:00是错误;
3. 月日不足两位必须补足,如2014/1/2是错误。

回答2:

你的变量borrowtime的值是空的,应该对它赋上值(如:2014-01-02 12:12:35)

回答3:

直接用DateTime.Parse 或者 TryParse 就好,Exact对个是的要求直接看msdn帮助
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;

// Parse date-only value with invariant culture.
dateString = "06/15/2008";
format = "d";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}

回答4:

字符串表示的格式必须与指定的格式完全匹配,比如"2015/3/4 0:00:00",第二个参数对应的就应该是 "yyyy/M/d h:mm:ss"

回答5:

borrowtime 是数据库里循环取的吗?如果是的话,数据库里面有空值或者错误格式了。不是你的代码问题。建议你换个简单的数据库进行测试代码。如果无误,就100%确定是数据问题。