我已经尝试了所有可能的在线解决方案,但无法弄清楚为什么我仍然收到此错误
“字符串未被识别为有效的日期时间”
有趣的是,我正在转换 2 个日期时间,一个是我的 gridview 中的单元格 3,另一个是单元格 7,但单元格 3 工作正常,但单元格 7 不想转换,它们都是相同的数据类型!!.我从我的 sql server 表中提取这些数据,数据类型为 varchar,但格式应为 mm/dd/yyyy。
我试过这个方法,但没有用:
foreach (GridViewRow gr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("chkItem");
if (cb.Checked)
{
DateTime ExpectedSubDate = DateTime.Parse(gr.Cells[3].Text);
DateTime strTargetDate = DateTime.ParseExact(gr.Cells[7].Text, "MM/DD/YYYY HH:MM:SS TT", System.Globalization.CultureInfo.InvariantCulture);
这个方法我也试过,也没用
DateTime strTargetDate = DateTime.Parse(gr.Cells[7].Text);
我也试过这种方式,但也没用:
DateTime strTargetDate = DateTime.ParseExact(gr.Cells[7].Text, "MM/DD/YYYY", System.Globalization.CultureInfo.InvariantCulture);
最佳答案
格式字符串是区分大小写的,否则它无法知道你希望它在哪里解析为月份或分钟。
对于日期和时间,例如 "11/15/2012 02:26:35 PM"
:
DateTime strTargetDate = DateTime.ParseExact(gr.Cells[7].Text, "MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
对于一个日期,例如 "11/15/2012"
:
DateTime strTargetDate = DateTime.ParseExact(gr.Cells[7].Text, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
关于c# - 字符串未被识别为使用 C# 的有效日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13406153/