我尝试比较两次,我parse'em然后我使用compareTo像:
Date one = new Date();
Date two = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm", java.util.Locale.getDefault());
try {
two = sdf.parse("12:33");
} catch (ParseException e1) {
e1.printStackTrace();
}
if (one.compareTo(two) < 0) {
//do this
}
当它不起作用时:(条件总是1) 我试着用这个:
Date one = new Date();
Date two = new Date();
boolean check = false;
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm", java.util.Locale.getDefault());
try {
two = sdf.parse("12:22");
check = two.after(one);
} catch (ParseException e1) {
e1.printStackTrace();
}
if(check)
// do this
}
第二个代码根本不起作用,我的崩溃
答案 0 :(得分:2)
您可以使用compareTo
。 compareTo()方法在接口 java.lang.Comparable 中定义。
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String getCurrentTime = sdf.format(c.getTime());
String getTestTime="09:45";
if (getCurrentTime .compareTo(getTestTime) < 0)
{
// Do your staff
Log.d("Return","getTestTime less than getCurrentTime ");
}
else
{
Log.d("Return","getTestTime older than getCurrentTime ");
}
答案 1 :(得分:0)
更改SimpleDateFormat,如下所示......
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
以下是模式:
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
这将有效....
UpDate:
看看它的工作方式..
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date inTime = sdf.parse("11:00");
Date outTime = sdf.parse("10:00");
if(inTime.compareTo(outTime) > 0){
Toast.makeText(this, "Out time should be greater than In time", Toast.LENGTH_SHORT).show();
}