【问题标题】:How to insert a SQLite record with a datetime set to 'now' in Android application?如何在 Android 应用程序中插入日期时间设置为“现在”的 SQLite 记录?
【发布时间】:2010-10-19 18:34:56
【问题描述】:

说,我们创建了一个表:

create table notes (_id integer primary key autoincrement, created_date date)

要插入记录,我会使用

ContentValues initialValues = new ContentValues(); 
initialValues.put("date_created", "");
long rowId = mDb.insert(DATABASE_TABLE, null, initialValues);

但是如何将 date_created 列设置为now?为了清楚起见,

initialValues.put("date_created", "datetime('now')");

不是正确的解决方案。它只是将列设置为“datetime('now')”文本。

【问题讨论】:

  • 这里的一个问题是Android 使用SQLite 作为数据库。您可以将列设置为某种类型,但这只是将列设置为“亲和力”。 SQLite 将允许您在任何列中放置任何值,而不管它是如何声明的。对于 SQLite,将字符串 'date' 放在任何地方都可以。 sqlite.org 有更详尽的解释。我在下面投票支持 e-satis 的答案,我就是这样做的(特别是 Java 方式)。

标签: android sqlite content-values


【解决方案1】:

您不能通过 Java 包装器“ContentValues”使用 datetime 函数。您可以使用:

  • SQLiteDatabase.execSQL,因此您可以输入原始 SQL 查询。

    mDb.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) ");
    
  • 或 java 日期时间功能:

    // set the format to sql date time
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    Date date = new Date();
    ContentValues initialValues = new ContentValues(); 
    initialValues.put("date_created", dateFormat.format(date));
    long rowId = mDb.insert(DATABASE_TABLE, null, initialValues);
    

【讨论】:

  • 请将代码重新格式化为“代码示例”。否则很好的答案。
  • 是 java.util.Date 还是 java.sql.Date?
  • java.util.Date,但我相信你也可以使用 java.sql.Date 日期。
【解决方案2】:

在我的代码中,我使用DATETIME DEFAULT CURRENT_TIMESTAMP 作为列的类型和约束。

在您的情况下,您的表定义将是

create table notes (
  _id integer primary key autoincrement, 
  created_date date default CURRENT_DATE
)

【讨论】:

    【解决方案3】:

    方法一

    CURRENT_TIME – Inserts only time
    CURRENT_DATE – Inserts only date
    CURRENT_TIMESTAMP – Inserts both time and date
    
    CREATE TABLE users(
        id INTEGER PRIMARY KEY,
        username TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    );
    

    方法二

    db.execSQL("INSERT INTO users(username, created_at) 
                VALUES('ravitamada', 'datetime()'");
    

    方法三 使用 java 日期函数

    private String getDateTime() {
            SimpleDateFormat dateFormat = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            Date date = new Date();
            return dateFormat.format(date);
    }
    
    ContentValues values = new ContentValues();
    values.put('username', 'ravitamada');
    values.put('created_at', getDateTime());
    // insert the row
    long id = db.insert('users', null, values);
    

    【讨论】:

    • 很好奇,您能展示一下如何将生成的字符串切换回 DATE 对象吗?
    • @erik 你能提供更多信息吗,我不完全明白你所说的。
    • 所以上面你正在获取一个 Date 对象并将其转换为要放置在 sqlite 列中的字符串.. 但是当你从数据库中提取该字符串时,你如何将它转换回 Date对象?
    • @erik SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); formatter.parse(created_at);
    • @erik 我认为我们不需要将字符串转换回日期,因为在数据库中我们有日期时间列,因此它将保存为日期时间。
    【解决方案4】:

    您可以使用几个选项:

    1. 您可以尝试改用字符串“(DATETIME('now'))”。
    2. 自己插入日期时间,即使用 System.currentTimeMillis()
    3. 创建 SQLite 表时,将 created_date 列的默认值指定为当前日期时间。
    4. 使用SQLiteDatabase.execSQL直接插入。

    【讨论】:

    • 数字 1 不起作用(至少在使用 ContentValuesupdate() 时不起作用,它只是将字符串 DATETIME('now') 放在列中。
    • 第二个时区有问题。我插入了一条带有DEFAULT CURRENT_TIMESTAMP 的记录,后来使用System.currentTimeMillis() 进行更新。我看到一个小时的差异。
    • @sooniln 您是否验证过 (DATETIME('now')) 确实会插入当前日期时间?
    • 如果要添加本地日期时间,请尝试使用 "datetime('now','localtime')" 代替
    【解决方案5】:

    对我来说,问题看起来像是您将"datetime('now')" 作为字符串而不是值发送。

    我的想法是找到一种方法来获取当前日期/时间并将其作为日期/时间值发送到您的数据库,或者找到一种使用SQLite内置(DATETIME('NOW'))参数的方法

    查看this SO.com question 的回答者 - 他们可能会引导您走向正确的方向。

    希望这会有所帮助!

    【讨论】:

      【解决方案6】:

      你可以使用java的功能是:

      ContentValues cv = new ContentValues();
      cv.put(Constants.DATE, java.lang.System.currentTimeMillis());  
      

      通过这种方式,您可以在数据库中保存一个数字。
      这个数字可以这样解释:

          DateFormat dateF = DateFormat.getDateTimeInstance();
          String data = dateF.format(new Date(l));
      

      你应该将数字插入到日期列中,而不是 l 到 new Date(l) 中。
      所以,你有你的约会。
      例如,我将这个号码保存在我的数据库中:1332342462078
      但是当我调用上面的方法时,我得到了这个结果:21-mar-2012 16.07.42

      【讨论】:

        【解决方案7】:

        根据@e-satis 的回答,我在“DBTools”类上创建了一个私有方法,因此现在添加当前日期非常容易:

        ...
        import java.text.SimpleDateFormat;
        import java.util.ArrayList;
        import java.util.Date;
        ...
                private String getNow(){
                    // set the format to sql date time
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date();
                    return dateFormat.format(date);
                }
        ...
        

        现在像这样使用它:values.put("lastUpdate", getNow());

        【讨论】:

          【解决方案8】:

          非常适合我:

              values.put(DBHelper.COLUMN_RECEIVEDATE, geo.getReceiveDate().getTime());
          

          将您的日期保存为长格式。

          【讨论】:

            【解决方案9】:

            这个代码示例可以做你想做的事:

            http://androidcookbook.com/Recipe.seam?recipeId=413

            【讨论】:

              【解决方案10】:

              在您尝试使用表达式“(DATETIME('now'))”插入默认时间戳的同时确保该字段未标记为“非空”

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多