我想计算今天的日期和数据库的日期之间的差异。我写了一个方法,但它不能完全发挥作用。我应该如何描绘两个日期之间的天数差异?
public ArrayList<String> roznicadni(){
ArrayList<String> roznicadni = new ArrayList<String>();
SQLiteDatabase db = DbHelper.getReadableDatabase();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String date = sdf.format(new Date());
String zapytanie = "SELECT "+date+" - "+Zlecenia_stale.Kolumny.datatstale+" AS xxx FROM "+Zlecenia_stale.NAZWA_TABELI+" WHERE id_portfela = "+WyborPortfela.portfel_id;
Cursor kursor = db.rawQuery(zapytanie, null);
for (kursor.moveToFirst(); !kursor.isAfterLast(); kursor.moveToNext()) {
roznicadni.add(1,kursor.getString(kursor.getColumnIndex("xxx")));
}
return roznicadni;
}
答案 0 :(得分:0)
使用TimeUnit
long dif = currentDate.getTime() - dbDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(dif);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(dif);
long diffInHours = TimeUnit.MILLISECONDS.toHours(dif);
答案 1 :(得分:0)
试试这个:
String database_date = "2016-01-08 12:56:50";
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
try {
Date oldDate = dateFormat.parse(database_date);
System.out.println(oldDate);
Date currentDate = new Date();
//difference in days,hours,minutes etc..
long diff = currentDate.getTime() - oldDate.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
if (oldDate.before(currentDate)) {
Log.e("oldDate", "is previous date");
Log.e("Difference: ", " seconds: " + seconds + " minutes: " + minutes
+ " hours: " + hours + " days: " + days);
}
} catch (ParseException e) {
e.printStackTrace();
}