Compare Java time. An instance of zoneddatetime, ignoring the seconds and milliseconds compared in Java 8
I'm looking for an equivalent method of joda time in Java 8. Compare org joda. time. An instance of datetime (specify time zone), ignoring seconds and milliseconds in the comparison, as shown below
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 milliseconds in the comparison
Fields with amplitude less than the lower limit specified by datetimefieldtype are ignored here
What is the equivalent method of using the java time API to perform the same operation in Java 8?
To tell you the truth, I try to implement the same function in Java 8
Solution
Due to the introduction of Lambdas and method references in java-8, it is very unnecessary to use special comparator classes, so they are in Java Does not exist in time You can write:
Comparator<zoneddatetime> comparator = Comparator.comparing( zdt -> zdt.truncatedTo(ChronoUnit.MINUTES));
Complete 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));