Reputation: 27909
I am looking for an equivalent way of Joda Time in Java 8 comparing instances of org.joda.time.DateTime
(with a time zone specified) ignoring seconds and milliseconds from 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
meaning that both the objects have been considered equal after ignoring seconds and milliseconds instants from the comparison.
Fields of a magnitude less than the lower limit specified with DateTimeFieldType
are ignored here.
What is the equivalent way of doing the same thing using the Java Time API in Java 8?
To be honest, I did not succeed to achieve the same in Java 8 with my attempts.
Upvotes: 11
Views: 13485
Reputation: 3409
Try ChronoUnit class.
long minutes = ChronoUnit.MINUTES.between(first, second);
Upvotes: 9
Reputation: 100339
As Java-8 introduced lambdas and method references, having dedicated Comparator
classes became mostly unnecessary, so they are absent in java.time
. You may write instead:
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));
Upvotes: 18