如何将当前时间与Android中存储在数据库中的时间进行比较

时间:2015-02-16 12:40:19

标签: java android

如何将当前日期与存储在数据库中的值进行比较?目前我的代码如下:

final String dDate = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4)));
final String dTime = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(5)));
Calendar calendar1 = Calendar.getInstance();
SimpleDateFormat formatter1 = new SimpleDateFormat("dd/M/yyyy");
String currentDate = formatter1.format(calendar1.getTime());

Calendar calendar2 = Calendar.getInstance();
SimpleDateFormat formatter2 = new SimpleDateFormat("h:mm");
String currentTime = formatter2.format(calendar2.getTime());
if(currentDate.compareTo(dDate)>=0) {
  if (currentDate.equals(currentDate)) {
    if (currentTime.compareTo(dTime) > 0) {
      myCheckBox.setChecked(true);
      myCheckBox.setEnabled(false);
    }
  }
}

2 个答案:

答案 0 :(得分:4)

此代码正常运行。看看

Calendar calendar1 = Calendar.getInstance();
SimpleDateFormat formatter1 = new SimpleDateFormat("dd/M/yyyy h:mm");
String currentDate = formatter1.format(calendar1.getTime());

final String dateString = cursor.getString(4);
final String timeString = cursor.getString(5);
String datadb =dateString+" "+timeString;

//  Toast.makeText(context,"databse date:-"+datadb+"Current Date :-"+currentDate,Toast.LENGTH_LONG).show();

if(currentDate.compareTo(datadb)>=0) {
    myCheckBox.setChecked(true);
    myCheckBox.setEnabled(false);
}

答案 1 :(得分:3)

您无法可靠地将日期作为字符串进行比较。您应该首先将光标中的日期和时间字符串组合成一个Date对象,然后将其与当前时间戳进行比较。

您的代码应该类似于

final String dDate = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4)));
final String dTime = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(5)));

SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yyyy h:mm");
Date dbDateTime = formatter.parse(dDate + " " + dTime);

if(new Date().compareTo(dbDateTime) >= 0) {
    myCheckBox.setChecked(true);
    myCheckBox.setEnabled(false);
}

在这里,SimpleDateFormat#parse()为我们提供了一个Date对象,其中包含从组合字符串初始化的日期和时间单位。然后可以简单地将其与返回系统当前日期和时间的new Date()对象进行比较。