C#DateTime异常错误

本文关键字:错误 异常 C#DateTime | 更新日期: 2023-09-27 18:07:44

我在excel中有一个日期列,它一直是2016年2月1日的格式(将来可能会改为2016年02月1日(,每一行都会添加到我的后台工作人员的数据表中。

在每个数据表行中循环,我获取日期列,并尝试更改几次日期,以获得正确的sqlite格式保存到数据库中。

见下文;

foreach datatablerow {
    //change dots to slashes 
    string dateString = Convert.ToString(rowData["Date"]).ToString().Replace(".", "/");
    //do DateTime C# Formatting..
    //This is causing the crash/exception
    DateTime _dateString = Convert.ToDateTime(dateString);
    //also have used & crahses as well
    //DateTime _dateString = DateTime.Parse(dateString);
    //Change agian to suit sqlite database entry - 2016/02/01
    string change_dateString = _dateString.ToString("yyyy-MM-dd");
    //Insert database data...
}

然而,我得到了System.FormatException:String在事务循环中没有被识别为有效的DateTime错误(即使在另一台计算机上,相同的事务使用上面的代码工作…

当我控制每个日期时,我可以看到它被正确转换为2016年2月1日,但DateTime部分崩溃了。。

C#DateTime异常错误

您尝试过设置不变区域性吗?

 DateTime yourdate= DateTime.ParseExact(rowData["Date"], "yyyy-MM-dd", 
                                       CultureInfo.InvariantCulture)

首先,删除此字符串操作。这是糟糕的编码。。。

string dateString = Convert.ToString(rowData["Date"]).ToString();

.Replace(".","/"(

更新

Sqlite中对DateTime值有一个常见的误解。为什么?

因为Sqlite没有内置DateTime值的存储数据类型。默认情况下,Sqlite在他的DataTypes:中处理这样的日期和时间值

  • 文本为ISO8601字符串("YYYY-MM-DD HH:MM:SS.SSS"(。

  • REAL作为儒略日的数字,是自公元前4714年11月24日格林尼治正午以来的天数,根据神秘的公历。

  • 整数作为Unix时间,指自1970-01-01 00:00:00 UTC以来的秒数。

如何捕捉错误

所以问题可能是

  • A:将错误的DataType强制转换为字符串

  • BTEXTColum(["Date"](中除ISO8601之外的其他日期格式

  • C:连接字符串中的其他Culture设置

试试这样的代码:

try
{
    string dateString = rowData["Date"].ToString();    
}
catch (System.Exception ex)
{
    throw new System.Exception("Couldn't get Data from Row! Maybe wrong DataType?")
}    
DateTime dateValue;
if (!DateTime.TryParse(dateString, out dateValue))
{
    // handle parse failure
    throw new System.Exception("Couldn't parse this String: " + dateString)
}