字符串在 C# 中不被识别为有效的日期时间
String is not recognised as valid datetime in C#
我有下面一行代码:
我正在阅读 excel(sent_date 列)中的 ex_date,其格式为 MM/DD/YYYY。
sent_date是日期类型,在数据库中以YYYY/MM/DD的格式保存。我尝试添加 Datetime.ParseExact。但它给出 "string is not recoganized as valid datetime".
string ex_date = dr[2].ToString();
DateTime date = new DateTime();
date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
string SentDateString = date.ToString("yyyy/MM/dd");
cmd.Parameters.AddWithValue("?sentdate", SentDateString);
如果您在 ParseExact: 上遇到错误,这意味着您从 excel 得到的值是错误的。确保所有值都正确。
正在运行:see here
编辑:
string ex_date = dr[2].ToString();
ex_date = ex_date.Split(' ')[0];
DateTime date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
string SentDateString = date.ToString("yyyy/MM/dd");
cmd.Parameters.AddWithValue("?sentdate", SentDateString);
因为您在 sql 日期时间列中传递字符串值。您需要将字符串转换为日期时间:
string SentDateString = date.ToString("yyyy/MM/dd");
DateTime SentDate = Convert.ToDateTime(SentDateString).Date;
cmd.Parameters.AddWithValue("?sentdate", sentDate);
希望对您有所帮助!
我有下面一行代码:
我正在阅读 excel(sent_date 列)中的 ex_date,其格式为 MM/DD/YYYY。 sent_date是日期类型,在数据库中以YYYY/MM/DD的格式保存。我尝试添加 Datetime.ParseExact。但它给出 "string is not recoganized as valid datetime".
string ex_date = dr[2].ToString();
DateTime date = new DateTime();
date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
string SentDateString = date.ToString("yyyy/MM/dd");
cmd.Parameters.AddWithValue("?sentdate", SentDateString);
如果您在 ParseExact: 上遇到错误,这意味着您从 excel 得到的值是错误的。确保所有值都正确。
正在运行:see here
编辑:
string ex_date = dr[2].ToString();
ex_date = ex_date.Split(' ')[0];
DateTime date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
string SentDateString = date.ToString("yyyy/MM/dd");
cmd.Parameters.AddWithValue("?sentdate", SentDateString);
因为您在 sql 日期时间列中传递字符串值。您需要将字符串转换为日期时间:
string SentDateString = date.ToString("yyyy/MM/dd");
DateTime SentDate = Convert.ToDateTime(SentDateString).Date;
cmd.Parameters.AddWithValue("?sentdate", sentDate);
希望对您有所帮助!