Andro Selva
Andro Selva

Reputation: 54322

How to compare time in java

I have the following format for time "hh:mm:ss" . Now I have two time values such as,

Date previous_time=20:50:55
Date current_time=19:50:55

And I am trying to compare it like this,

if(previous_time.after(current_date)){
  Log.i("Time Comparision","before is true");
      System.out.println("before");  
}
else if(current_time.after(previous_time)){
  Log.i("Time Comparision","after is true");
  System.out.println("after");   
}
else {
  System.out.println("nothing");
  Log.i("Time Comparision not happened","");
}

But both my if conditions are not working. My question is, how to compare two times when they are in the above mentioned format?

Upvotes: 1

Views: 2112

Answers (2)

Ondřej Holman
Ondřej Holman

Reputation: 148

You can try to compare it via Date.getTime() function, which returns milliseconds after 1/1/1970.

Upvotes: 2

Sarel Botha
Sarel Botha

Reputation: 12700

In your first line of code you refer to current_date not current_time.

Either that's the problem or the two dates are equal, which would execute the part in else.

Upvotes: 3

Related Questions