Compare LocalDateTime without nano second in java 8

Niraj Sonawane :

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  
Ousmane D. :

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))); 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=442616&siteId=1