Comparing instances of java.time.ZonedDateTime ignoring seconds and millisecond moments from comparisons in Java 8

I am looking for an equivalent Joda Time method in Java 8 comparing org.joda.time.DateTime instances (with the specified time zone), ignoring the seconds and milliseconds from the comparisons as follows.

 DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss:SSS a Z").withZone(DateTimeZone.forID("Asia/Kolkata")); DateTime first = formatter.parseDateTime("16-Feb-2012 12:03:45:999 AM +05:30"); DateTime second = formatter.parseDateTime("16-Feb-2012 12:03:55:999 AM +05:30"); DateTimeComparator comparator = DateTimeComparator.getInstance(DateTimeFieldType.minuteOfHour()); int compare = comparator.compare(first, second); System.out.println("compare : " + compare); 

The comparison returns 0 , which means that both objects are considered equal after ignoring the seconds and millisecond moments from the comparison.

Fields whose value is less than the lower limit specified in DateTimeFieldType are ignored here.

What is the equivalent way to do the same using the Java Time API in Java 8?

Honestly, I was not able to achieve the same in Java 8 with my attempts.

+6
source share
2 answers

Since Java-8 introduced references to lambdas and methods, the highlighted Comparator classes became mostly unnecessary, which is why they were missing in java.time . Instead, you can write:

 Comparator<ZonedDateTime> comparator = Comparator.comparing( zdt -> zdt.truncatedTo(ChronoUnit.MINUTES)); 

Full example:

 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy hh:mm:ss:SSS a X") .withLocale(Locale.ENGLISH).withZone(ZoneId.of("Asia/Kolkata")); ZonedDateTime first = ZonedDateTime.parse("16-Feb-2012 12:03:45:999 AM +0530", formatter); ZonedDateTime second = ZonedDateTime.parse("16-Feb-2012 12:03:55:999 AM +0530", formatter); Comparator<ZonedDateTime> comparator = Comparator.comparing( zdt -> zdt.truncatedTo(ChronoUnit.MINUTES)); System.out.println(comparator.compare(first, second)); 
+9
source

Try the ChronoUnit class.

 long minutes = ChronoUnit.MINUTES.between(first, second); 
+7
source

All Articles