使用 Java 的时间差异 - 从午夜之前到午夜之后



我正在开发一个程序,该程序将返回两个时间点之间经过的时间差(多少小时,分钟)。 我需要能够计算时间,如果时间是,比如说,晚上 11:00 到凌晨 3:00。 我将如何做到这一点,以及计算从上午 8:00 到下午 5:00 的时间?

谢谢!

如果有人正在寻找解决方案,您可以像这个答案一样做

String time = "22:00-01:05";
String[] parts = time.split("-");
LocalTime start = LocalTime.parse(parts[0]);
LocalTime end = LocalTime.parse(parts[1]);
if (start.isBefore(end)) { // normal case
    System.out.println(Duration.between(start, end));
} else { // 24 - duration between end and start, note how end and start switched places
    System.out.println(Duration.ofHours(24).minus(Duration.between(end, start)));
}
public static void main(String[] av) {
    /** The date at the end of the last century */
    Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
    /** Today's date */
    Date today = new Date();
    // Get msec from each, and subtract.
    long diff = today.getTime() - d1.getTime();
    System.out.println("The 21st century (up to " + today + ") is "
        + (diff / (1000 * 60 * 60 * 24)) + " days old.");
}

最新更新