c# 读取sqlite3中的SQL type=TIMESTAMP字段时报错

2023-12-22 10:40:18
public static DateTime safeGetDateTime(SQLiteDataReader reader, string field)
        {
            int column = reader.GetOrdinal(field);
            if (!reader.IsDBNull(column))
            {
                return reader.GetDateTime(column);
            }

            return DateTime.Now;
        }
private void process(string dbPath)
        {
 
            int nNum = 0;
            SQLiteConnection connection = null;
            try
            {
                connection = new SQLiteConnection("Data Source=" + dbPath + ";version=3;new=False;datetimeformat=CurrentCulture;");
                connection.Open();
                SQLiteCommand command = new SQLiteCommand(connection);
                command.CommandText = "select    ZADDRESS,ZDURATION,ZORIGINATED, ZDATE ,Cast(ZDATE as nvarchar(20)) as ZDATE_NEW from  ZCALLRECORD ;";
                SQLiteDataReader reader = command.ExecuteReader(); 
             
                while (reader.Read())
                {
                    try
                    {
                        DateTime dateTime = SqliteDBTool.safeGetDateTime(reader, "ZDATE") ;
                        string  number = Encoding.UTF8.GetString(SqliteDBTool.safeGetBytes(reader, "ZADDRESS"));
                         
                        int dateTimeIndex=  reader.GetOrdinal("ZDATE_NEW") ; 
                        var date=reader["ZDATE_NEW"].ToString(); 
                        string duration = SqliteDBTool.safeGetFloat(reader, "ZDURATION").ToString("F1");

                    }
                    catch(Exception e)
                    {
                        add_log(e.ToString());
                    }
                }

                 
                reader.Close();
                connection.Close();
                connection.Dispose();
                 
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                if (connection != null)
                {
                    connection.Close();
                    connection.Dispose();
                }
            }
        }

process(@"C:\CallHistory.storedata");

使用SQLite抛出异常: 该字符串未被识别为有效的 DateTime 错误。

参考如下?

c# - sqlite throwing a "String not recognized as a valid datetime" - Stack Overflow

但我就想把数据读出来,就要使用Cast(ZDATE as nvarchar(20)) as ZDATE_NEW 把数据格式转一下,然后再用? ? ? ? var date=reader["ZDATE_NEW"].ToString(); 读出数据然后再慢慢转换

double timestamp = 6220820844.00406;

? ? ? ? ? ? // 转换为 DateTime
? ? ? ? ? ? DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds((long)timestamp);
? ? ? ? ? ? DateTime dateTime = dateTimeOffset.UtcDateTime;
? ? ? ? ? ? add_log(dateTime.ToString("s"));

select ZADDRESS,ZDURATION,ZORIGINATED,ZDATE ,Cast(ZDATE as nvarchar(20)) as ZDATE_NEW from ?ZCALLRECORD ;

?

文章来源:https://blog.csdn.net/babytiger/article/details/135145127
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。