c# - 字符串未被识别为使用 C# 的有效日期时间

标签 c# asp.net

我已经尝试了所有可能的在线解决方案,但无法弄清楚为什么我仍然收到此错误 “字符串未被识别为有效的日期时间” 有趣的是,我正在转换 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);

引用:Custom Date and Time Format Strings

关于c# - 字符串未被识别为使用 C# 的有效日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13406153/

相关文章:

asp.net - 如何将错误从一个操作传递到另一个操作

c# - 在没有用户名和密码的情况下使用 ASP.NET 获取 Active Directory 信息

c# - 在 C# 2.0 中使用 Invoke 调用时,参数从 null 转换为 DateTime.MinValue

c# - 如何等待 SqlTransaction 提交而不是抛出 SqlException

c# - out 函数参数的棘手 C# 语法

asp.net - 没有 Eval 的 GridGroupHeaderItem.AggregatesValues

c# 将自定义方法添加到列表

c# - 标签中的装饰和扩展文本

c# - 在 .NET 中实现加密/解密流的正确方法?

c# - 如何使用包含资源值的IController Execute()返回View?