S'ed Sckizo S'ed Sckizo - 4 months ago 80
Java Question

compare two times format HH:MM java-android

i try to compare two times , i parse'em then i used compareTo like :

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
}


and when it doen't work : ( the condition is always 1 )
i tried to use this :

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
}


the second code doesn't work at all , my up get crashes

Answer

You can use compareTo . compareTo() method is defined in interface 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 "); 
}