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
The compareTo() method of LocalDateTime class in Java is used to compare this date-time to the date-time passed as the parameter.
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.
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.
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With