簡體   English   中英

如何比較 Java 8 中 Date 對象之間的時間?

[英]How can I compare time of the day between Date objects in Java 8?

給定兩個包含小時和分鍾的Date對象,我如何優雅地找出其中哪一個具有一天中最早的時間?

例如,如果date12018-01-01 at 09:00 ,而date22018-01-02 at 08:00 ,那么根據本規范, date2 < date1

如果您之前轉換DateLocalTime可以使用 LocalTime 的compareTo -Method。

像這樣轉換(在https://www.baeldung.com/java-date-to-localdate-and-localdatetime找到):

public static LocalTime convertToLocalTimeViaInstant(Date dateToConvert) {
    return dateToConvert.toInstant()
            .atZone(ZoneId.systemDefault())
            .toLocalTime();
}

並像這樣比較:

time1.compareTo(time2);

如果你想使用一種方法,你可以使用這樣的轉換:

public static int compareTimeOfDates(Date date1, Date date2) {
    return convertToLocalTimeViaInstant(date1).compareTo(convertToLocalTimeViaInstant(date2));
}

您可以嘗試執行以下操作:

boolean compareTime(Date date1, Date date2) {
    DateFormat df = new SimpleDateFormat("HHmm");
    int timeDate1 = Integer.valueOf(df.format(date1));
    int timeDate2 = Integer.valueOf(df.format(date2));
    return timeDate1 >= timeDate2;
}

編輯2:

//just a sample. base on your case, set the date you have to here.
        Date date1 = Calendar.getInstance().getTime(); 
        Date date2 = Calendar.getInstance().getTime();

        LocalDateTime lcdate1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime lcdate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();


        int date1Hour = lcdate1.getHour();
        int date1Minute = lcdate1.getMinute();

        int date2Hour = lcdate2.getHour();
        int date2Minute = lcdate2.getMinute();

更多細節在這里: https : //docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html

希望這有幫助。

int compareTimeOfDate(Date a, Date b) {
    LocalDateTime localA = a.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    int hourA = localA.getHour();
    int minuteA = localA.getMinute();

    LocalDateTime localB = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    int hourB = localB.getHour();
    int minuteB = localB.getMinute();

    if (hourA == hourB && minuteA == minuteB) {
        return 0;
    }

    if (hour1 < hour2 || hour1 == hour2 && minute1 < minute2) {
        return -1;
    }

    return 1;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM