c# - 当日期存储为刻度时,为什么strftime()在Sqlite中不起作用?

标签 c# sqlite

我有以下代码:

    [Test]
    public void SqliteTest()
    {
        var insertQuery = @"insert into MetricData (Date) Values (@date)";
        var selectQuery = @"select strftime('%Y',Date) as 'year', Date from MetricData";

        var connectionString = "Data Source=:memory:;Version=3;DateTimeFormat=Ticks;";
        using (var db = new SQLiteConnection(connectionString))
        {
            db.Open();
            DatabaseSchemaBuilder.InitializeSchema(db);

            var testDate = DateTime.Now;
            using (var cmd = new SQLiteCommand(insertQuery, db))
            {
                cmd.Parameters.AddWithValue("@date", testDate);
                cmd.ExecuteNonQuery();
            }

            using (var cmd = new SQLiteCommand(selectQuery, db))
            {
                using (var reader = cmd.ExecuteReader())
                {
                    reader.Read();
                    var queriedDate = reader.GetDateTime(1);
                    var year = reader.GetString(0);

                    Assert.AreEqual(testDate, queriedDate);
                    Assert.AreEqual("2013", year);
                }
            }
        }
    }


当我运行此代码时,第一个断言通过了,但是第二个断言失败了,年份等于1968(其他格式值也不正确,例如,月返回为19)。

查看原始查询输出时,年份结果为1968,日期为635120225608999130

为什么strftime()在这种情况下不能正常工作?

编辑:
只需添加一下,我已将日期列定义为Date integer。另外,如果我在连接字符串中不包含DateTimeFormat=Ticks,则所有断言都将通过。

最佳答案

Date作为Integer中的Sqlite使用Unix Time,它允许最早的日期为1970-01-01 00:00:00 UTC。因此,1968年的值将是一个错误,并且不会通过Assert.AreEqual("2013",year)

Documentation

并且在连接字符串中删除DateTimeFormat=Ticks;意味着您将使用默认的ISO8601,该默认值允许日期在1970-01-01之前,并且很有可能是Assert通过的原因。

Reference

关于c# - 当日期存储为刻度时,为什么strftime()在Sqlite中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18221407/

相关文章:

c# - volatile IEnlistmentNotification 和 TransactionScope.AsyncFlowEnabled = true

c# - 使用VS2012框架的IBM DB2连接4

android - 下面的 SQLite 语句抛出异常 : Table TABLE_NAME has no column named COLUMN_NAME 有什么问题

c# - SubSonic 无法识别 SQLite 外键

c# - 了解 C# 中运行时代码生成的各种选项(Roslyn、CodeDom、Linq 表达式,...?)

c# - 返回列表值列表(合并)

c# - 如何在自托管 (AppSelfHostBase) Servicestack 服务 (RequestStream) 上设置文件大小限制?

android - 数据库未在 OnePlus 2 中正确复制

android - 从 SQLite 数据库中检索行中的特定数据

android - 如何从 Android 上的 XML 文件加载 SQL 查询?