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

chhkpiq4  于 2023-02-23  发布在  SQLite
关注(0)|答案(6)|浏览(882)

我想在SQLite中创建一个表,其中一个字段是日期,当前示例的日期和时间应该保存在其中。我应该使用哪种数据类型?
我计划使用“时间戳”。如何插入当前时间戳值到字段?以及如何写入此日期字段的内容值?

y53ybaqx

y53ybaqx1#

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()));
zlwx9yxi

zlwx9yxi2#

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

使用此site进行进一步参考。

o8x7eapl

o8x7eapl3#

要获取当前本地(系统)时间,请添加“localtime”选项:
选择日期时间('现在','本地时间');

insrf1ej

insrf1ej4#

我在我的应用程序中经常使用时间戳。对我来说,保存时间戳的最好方法是以毫秒为单位进行转换。之后,很容易将其转换为任何语言环境。
如果你需要当前的时间,使用System.currentTimeMillis()。内容值很容易使用,你只需要加上字段和值,比如:

ContentValues ins_reminder = new ContentValues();
ins_reminder.put("REMIND_TIMESTAMP", System.currentTimeMillis());
yxyvkwin

yxyvkwin5#

从SQLite 3.38.0开始,有一个unixepoch()函数可以返回整数形式的UNIX时间戳,其作用与strftime('%s')相同。
参考文献:

2ledvvac

2ledvvac6#

在我的情况下,我希望有一个时间戳与分数秒。

如何获得秒的分数?

要获取以秒为单位的值,请使用ado.netsqlite.net-core执行以下操作

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

当前时间戳只有秒

built in keywordCURRENT_TIMESTAMP的精度只有YYYY-MM-DD HH:MM:SS,如下所示

SELECT 'A   ' as example, (strftime('%Y-%m-%d %H:%M:%S:%s')) as Better_TimeStamp
       , 'With fractions of a seccond' as comment 
UNION ALL
SELECT 'B  ', CURRENT_TIMESTAMP
            , 'only YYYY-MM-DD HH:MM:SS  without fractions of a seccond'

这在CREATE的DEFAULT子句中进行了说明
如果列的缺省值为CURRENT_TIME、CURRENT_DATE或CURRENT_TIMESTAMP,则新行中使用的值是当前UTC日期和/或时间的文本表示形式。
格式为

  • HH:MM:SS表示当前时间
  • YYYY-MM-DD表示当前日期
  • YYYY-MM-DD HH:MM:SS用于当前时间戳

在c#中使用它的示例

以下内容基于bulk insert in sqlite with ado.net

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();
}

相关问题