【问题标题】:Inserting datetime in sqlite database android在sqlite数据库android中插入日期时间
【发布时间】:2015-08-28 04:26:06
【问题描述】:

如何使用 contentvalues 而不使用原始查询在我的 sqlite 数据库中插入日期时间数据?

datetime('now') 插入自身(文本)而不是时间,我可以在当前时间中添加额外的小时数吗?

就像,当我按下按钮“1HOUR”时,它会在 sqlite 数据库中插入当前时间 + 1 小时..谢谢,有点困惑..

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    将日期/时间转换为毫秒,你会得到一个long。然后你只需在数据库中插入long 值。

    如果日期/时间值以毫秒为单位,您可以将它们相加。

    --已编辑--

        Date myDate = new Date();
        long timeMilliseconds = myDate.getTime();
        //add 1 hour
        timeMilliseconds = timeMilliseconds + 3600 * 1000; //3600 seconds * 1000 milliseconds
        //To convert back to Date
        Date myDateNew = new Date(timeMilliseconds);
    

    在 SQLite 中,java long 值存储为 int

    【讨论】:

    • 你能告诉我语法吗,我真的一无所知..我怎样才能转换它?
    • 谢谢!!!,这就是我需要的......当我通过 long 插入它时,我可以按照我想要的方式检索和转换它,但是当我通过格式化插入它时(YYYY -DD-MM)我无法检索它,如果我通过 long 检索它只会检索年份,如果通过 getString,它只是一个字符串,我无法将其转换为实际的毫,有解决方法吗?我可以使用 long 方法,但如果它是可读的,在我的数据库中会更方便..谢谢..真的帮助了我
    【解决方案2】:

    您不能通过 Java 包装器“ContentValues”使用日期时间函数。您可以通过这种方式实现:

    1) 可以使用SQLiteDatabase.execSQL(原始SQL查询)

     dbObj.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) ");
    

    2) 你可以使用 SimpleDateFormat

    // setting 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_time", dateFormat.format(date));
    long recordId = mDb.insert(DB_TABLE_NAME, null, initialValues);
    

    3)您将日期值以(长类型)毫秒存储在数据库中,并且为了显示您可以对其进行格式化,

     import java.text.DateFormat;
     import java.text.SimpleDateFormat;
     import java.util.Calendar;
    
    System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS"));
    
    // Return date in specified format.
    // milliSeconds Date in milliseconds
    // dateFormat Date format 
    // return date as string in specified format
    
    public static String formatDate(long milliSeconds, String dateFormat)
    {
    
        DateFormat formatter = new SimpleDateFormat(dateFormat);
    
    // Create a calendar object that will convert the date and time value in milliseconds to date. 
       Calendar calendar = Calendar.getInstance();
     calendar.setTimeInMillis(milliSeconds);
     return formatter.format(calendar.getTime());
       }
     }
    

    1 秒 = 1000 毫秒,所以如果你想增加 1 小时,请使用这个公式

      currentTImeMilli + (60 * 60 * 1000)
    

    【讨论】:

    • 我使用了第二个,但使用 system.currentmills,然后对其进行格式化.. 谢谢。它有效,现在我有一个新问题,如果我检索日期“2012-10-28 09:58:15”,我如何将其转换为 system.currentmillis 使用的格式?我需要它,因为我的应用程序需要将当前时间与某个时间进行比较(在本例中为 +1 小时)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    相关资源
    最近更新 更多