两个日期正在比较,但时间没有正确比较。 这是我的代码
final String setdate = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4)));
final String settime = 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(setdate)>=0)
{
if(currentTime.compareTo(settime)>=0) {
myCheckBox.setChecked(true);
myCheckBox.setEnabled(false);
}
}
如何比较两次。在数据库日期和时间字段不同。所以请帮助我。
答案 0 :(得分:14)
试试这个:
private boolean checktimings(String time, String endtime) {
String pattern = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
Date date1 = sdf.parse(time);
Date date2 = sdf.parse(endtime);
if(date1.before(date2)) {
return true;
} else {
return false;
}
} catch (ParseException e){
e.printStackTrace();
}
return false;
}
答案 1 :(得分:8)
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);
}
答案 2 :(得分:0)
答案 3 :(得分:0)
我认为您正在询问如何从日期和时间的两个单独字段中构建日期时间。这很简单。您可以使用SimpleDateFormat
执行此操作:
final String dateString = cursor.getString(4);
final String timeString = cursor.getString(5);
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy h:mm");
Date dbDate = sdf.parse(dateString + " " + timeString);
int compareToNow = new Date().compareTo(dbDate);
答案 4 :(得分:0)
public static boolean isTimeGreater(String date, String time) {
Date currentTime, pickedTime;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String currentTimeString = sdf.format(new Date());
try {
currentTime = sdf.parse(currentTimeString);
pickedTime = sdf.parse(date + " " + time);
Log.e("Ketan", "Current Date: " + currentTime);
Log.e("Ketan", "Picked Date: " + pickedTime);
/*compare > 0, if date1 is greater than date2
compare = 0, if date1 is equal to date2
compare < 0, if date1 is smaller than date2*/
if (pickedTime.compareTo(currentTime) > 0) {
Log.e("Ketan", "Picked Date is Greater than Current Date");
return true;
} else {
Log.e("Ketan", "Picked Date is Less than Current Date");
return false;
}
} catch (ParseException e) {
e.printStackTrace();
}
return true;
}
答案 5 :(得分:-1)
在Java中,有一种方法可以比较两个日期和时间
您必须在JAVA中以DATE格式格式化日期和时间。
之后使用下面的代码
date1.compareTo(date2);
希望上面的代码可以帮到你。
如果您需要我的帮助,请告诉我。