在SQLite数据库中插入当前日期和时间

48

我想在SQLite中创建一个表格,其中一个字段是日期,应该保存当前实例的日期和时间。我应该使用什么数据类型?

我计划使用“timestamp”。如何将当前时间戳值插入到字段中?还有如何编写与此日期字段相关的内容值?

6个回答

79

SQLite支持标准SQL变量CURRENT_DATECURRENT_TIMECURRENT_TIMESTAMP:

INSERT INTO Date (LastModifiedTime) VALUES(CURRENT_TIMESTAMP)

在SQLite中,默认的日期/时间数据类型TEXT

ContentValues不允许使用通用SQL表达式,只能使用固定值,因此您需要在Java中读取当前时间:

cv.put("LastModifiedTime",
       new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

选择这三个常量返回值,但是我能够使时间不偏移六小时的唯一方法是使用上面David Garoutte的答案。 - Gary Z
1
@GaryZ 默认情况下,SQLite 的日期是以协调世界时(UTC)表示的。如果您期望它们以本地时区表示,则您的期望是错误的。 :-) - CL.

30
INSERT INTO Date (LastModifiedTime) VALUES(DateTime('now'))

请使用此网站以供参考。


这是插入当前时间戳值吗? - Jesbin MJ

5

要获取当前本地(系统)时间,请添加'localtime'选项:

select datetime('now', 'localtime');


1
我在我的应用程序中经常使用时间戳。对我而言,保持时间戳的最佳方法是将其转换为毫秒。之后很容易将其转换为任何语言环境。
如果您需要当前时间,请使用System.currentTimeMillis()。 内容值很容易使用,您只需添加字段和值,例如:
ContentValues ins_reminder = new ContentValues();
ins_reminder.put("REMIND_TIMESTAMP", System.currentTimeMillis());

0
自从 SQLite 3.38.0 版本以来,新增了一个名为 unixepoch() 的函数,它返回整数形式的 UNIX 时间戳。与 strftime('%s') 执行相同的操作。
参考资料:

0

在我的情况下,我想要一个带有秒的小数部分的时间戳。

  • 关键字 CURRENT_TIMESTAMP 只有精度为 YYYY-MM-DD HH:MM:SS(请参见 文档 DEFAULT 子句)。
  • 函数 strftime() 可以返回秒的小数部分。

使用 strftime()INSERT 中的示例

INSERT INTO YourTable (TimeStamp)  
       VALUES (strftime('%Y-%m-%d %H:%M:%S:%s'))

CURRENT_TIMESTAMPstrftime()的比较

SELECT 'CURRENT_TIMESTAMP' as Timestamp_Command, 
        CURRENT_TIMESTAMP as TimeStamp_Precision,
       'only seconds'  as Timestamp_Comment 
UNION ALL           
SELECT 'strftime(%Y-%m-%d %H:%M:%S:%s)' as Timestamp_Command, 
        (strftime('%Y-%m-%d %H:%M:%S:%s')) as TimeStamp_Precision,
        'with fraction of a second' as Timestamp_Comment 

Sqlite_Select_Current_Timestamp_vs_strftime

在C#中使用的示例

以下内容基于使用ADO.NET进行SQLite批量插入

public static void InsertBulk(SqliteConnection connection)
{
    connection.Open();
    using (var transaction = connection.BeginTransaction())
    {
       var command = connection.CreateCommand();
       command.CommandText =
            @"INSERT INTO BulkInsertTable (CreatedOn, TimeStamp)
              VALUES ($createdOn, strftime('%Y-%m-%d %H:%M:%S:%s'))";

       var parameter3 = command.CreateParameter();
       parameter3.ParameterName = "$createdOn";
       command.Parameters.Add(parameter3);  

       // Insert a lot of data
       // calling System.DateTime.Now outside the loop is faster
       var universalTime = System.DateTime.Now.ToUniversalTime();
       for (var i = 0; i < 15_000; i++)
       {
          parameter3.Value = System.DateTime.Now.ToUniversalTime();
          // faster 
          // parameter3.Value = universalTime;
          command.ExecuteNonQuery();
        }
        transaction.Commit();
    }
    connection.Close();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接