猿问

如何比较 Java 8 中 Date 对象之间的时间?

给定两个Date包含小时和分钟的对象,我如何优雅地找出其中哪一个具有一天中最早的时间?

例如,如果date12018-01-0109:00,并且date22018-01-0208:00,那么这个规范,date2 < date1


叮当猫咪
浏览 209回答 3
3回答

郎朗坤

如果您转换之前,您可以使用compareTo-Method 。LocalTimeDate像这样转换(在https://www.baeldung.com/java-date-to-localdate-and-localdatetime找到):public static LocalTime convertToLocalTimeViaInstant(Date dateToConvert) {&nbsp; &nbsp; return dateToConvert.toInstant()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .atZone(ZoneId.systemDefault())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toLocalTime();}并像这样比较:time1.compareTo(time2);如果你想使用一种方法,你可以使用这样的转换:public static int compareTimeOfDates(Date date1, Date date2) {&nbsp; &nbsp; return convertToLocalTimeViaInstant(date1).compareTo(convertToLocalTimeViaInstant(date2));}

交互式爱情

您可以尝试执行以下操作:boolean compareTime(Date date1, Date date2) {&nbsp; &nbsp; DateFormat df = new SimpleDateFormat("HHmm");&nbsp; &nbsp; int timeDate1 = Integer.valueOf(df.format(date1));&nbsp; &nbsp; int timeDate2 = Integer.valueOf(df.format(date2));&nbsp; &nbsp; return timeDate1 >= timeDate2;}

不负相思意

编辑2://just a sample. base on your case, set the date you have to here.&nbsp; &nbsp; &nbsp; &nbsp; Date date1 = Calendar.getInstance().getTime();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Date date2 = Calendar.getInstance().getTime();&nbsp; &nbsp; &nbsp; &nbsp; LocalDateTime lcdate1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();&nbsp; &nbsp; &nbsp; &nbsp; LocalDateTime lcdate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();&nbsp; &nbsp; &nbsp; &nbsp; int date1Hour = lcdate1.getHour();&nbsp; &nbsp; &nbsp; &nbsp; int date1Minute = lcdate1.getMinute();&nbsp; &nbsp; &nbsp; &nbsp; int date2Hour = lcdate2.getHour();&nbsp; &nbsp; &nbsp; &nbsp; int date2Minute = lcdate2.getMinute();更多细节在这里:https : //docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html希望这有帮助。
随时随地看视频慕课网APP

相关分类

Java
我要回答