Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare LocalDateTime without nano second in java 8

Tags:

java

java-8

I want to compare 2 LocalDateTime objects without considering nanoseconds. This is how I am currently doing. is there any better way of doing this?

LocalDateTime object1 = LocalDateTime.of(2014, 3, 30, 12, 30, 23, 12000);
LocalDateTime object2 = LocalDateTime.of(2014, 3, 30, 12, 30, 23, 12004);

System.out.println(object1.isEqual(object2)); // false

LocalDateTime  objec1tWithoutNano = object1.minusNanos(object1.getNano());
LocalDateTime  objec2tWithoutNano = object2.minusNanos(object2.getNano());

System.out.println(objec1tWithoutNano.isEqual(objec2tWithoutNano)); // true  
like image 927
Niraj Sonawane Avatar asked Nov 30 '17 00:11

Niraj Sonawane


People also ask

Can you compare LocalDateTime in Java?

The compareTo() method of LocalDateTime class in Java is used to compare this date-time to the date-time passed as the parameter.

What is the difference between two LocalDateTime in Java 8?

Here's a way to calculate the difference although not necessarily the fastest: LocalDateTime fromDateTime = LocalDateTime. of(1984, 12, 16, 7, 45, 55); LocalDateTime toDateTime = LocalDateTime. of(2014, 9, 10, 6, 40, 45); LocalDateTime tempDateTime = LocalDateTime.

How do I compare two LocalDate objects?

LocalDate compareTo() Method The method compareTo() compares two instances for the date-based values (day, month, year) and returns an integer value based on the comparison. 0 (Zero) if both the dates represent the same date in calendar. Positive integer if given date is latter than the otherDate.


1 Answers

I'd recommend that you proceed with whatever approach is most readable to you as most of the methods within the LocalDateTime API already return a new instance on each method invocation so there is a minimal performance deficit if any between the different ways you could accomplish the task at hand. for example, the truncateTo could be used to return the same result as your example with the use of minusNanos:

System.out.println(object1.truncatedTo(ChronoUnit.SECONDS)
    .isEqual(object2.truncatedTo(ChronoUnit.SECONDS))); 
like image 76
Ousmane D. Avatar answered Oct 25 '22 15:10

Ousmane D.