I am facing the issue with localDateTime in JAVA.
I am using the isAfter function to compare the two date time but only returns correct value if there was a variation in time but not the date.
Program:
import java.time.LocalDateTime;
public class LocalDatTimeVerificaiton {
public static void main(String[] args) throws Exception {
LocalDateTime dateTime=LocalDateTime.now();
System.out.println(dateTime);
Thread.sleep(10000);
LocalDateTime dateTime1=LocalDateTime.now();
System.out.println(dateTime1);
if(dateTime1.isAfter(dateTime)){
System.out.println(dateTime+" After "+dateTime1);
}
if(dateTime1.isAfter(dateTime)){
System.out.println(dateTime1+" After "+dateTime);
}else{
System.out.println(dateTime1+" Not After "+dateTime);
}
}
}
Output Actual
2017-08-11T18:32:00.466
2017-08-11T18:32:10.467
2017-08-11T18:32:00.466 After 2017-08-11T18:32:10.467
2017-08-11T18:32:10.467 After 2017-08-11T18:32:00.466
Expected
2017-08-11T18:32:00.466
2017-08-11T18:32:10.467
2017-08-11T18:32:00.466 After 2017-08-11T18:32:10.467
2017-08-11T18:32:10.467 Not After 2017-08-11T18:32:00.466
Is this the expected behavior or is am I missing something?
Why do you expect 18:32:10
to be before 18:32:00
?
You may be misled by a typo in your code:
if (dateTime1.isAfter(dateTime)) {
System.out.println(dateTime + " After " + dateTime1);
^^^ ^^^
}
Should probably be:
if (dateTime1.isAfter(dateTime)) {
System.out.println(dateTime1 + " After " + dateTime);
^^^ ^^^
}