Android:从SQLite中提取两个Datetime

时间:2015-10-08 14:14:40

标签: java android sqlite datetime

我在SQLite中的数据库中有这样的数据。

ID   COLUMN_SBEGIN         COLUMN_SEND
1    2015-10-08 22:00:00   2015-10-09 08:00:00

我希望从22:00:0008:00:00获得多少小时。你有什么想法吗?

这是我的代码!

public void sleepProcess() throws ParseException {
    cursor = getContentResolver().query(ProviderSleep.CONTENT_URI, Helper.ALL_SLEEP,null,null,null,null);
    cursor.moveToFirst();
    String temp = cursor.getString(cursor.getColumnIndex(Helper.COLUMN_SBEGIN)); //get the time data
    String temp2 = cursor.getString(cursor.getColumnIndex(Helper.COLUMN_SEND)); //get the time data

    java.text.DateFormat df = new java.text.SimpleDateFormat("hh:mm:ss");
    java.util.Date t1 = df.parse(temp);
    java.util.Date t2 = df.parse(temp2);
    long sumSleep = t2.getTime() - t1.getTime();

    //sumSleep should in Hours(Integer)

    if(sumSleep < 8){
        sleep.setImageResource(R.drawable.ic_close);
    }else{
        sleep.setImageResource(R.drawable.ic_check);
    }

}

2 个答案:

答案 0 :(得分:0)

这为您提供了以毫秒为单位的差异:

long sumSleep = t2.getTime() - t1.getTime();

所以要根据this answer将其转换为小时数Java 5

TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(sumSleep))

或者,Java 4或更少

int hours   = (int) ((sumSleep / (1000*60*60)) % 24);

答案 1 :(得分:0)

变量sumSleep包含t1t2之间的差异(以毫秒为单位)。所以你只需要把它转换成几小时。

long millisInHour = 1000 * 60 * 60;
long elapsedHours = sumSleep / millisInHour;