在Java程序設(shè)計(jì)中,當(dāng)需要對(duì)時(shí)間進(jìn)行計(jì)算時(shí),經(jīng)常需要對(duì)小時(shí)和分鐘進(jìn)行相加減操作。下面是幾個(gè)示例:
// 計(jì)算兩個(gè)時(shí)間之差 LocalTime time1 = LocalTime.of(10, 30); LocalTime time2 = LocalTime.of(11, 45); Duration duration = Duration.between(time1, time2); System.out.println("時(shí)間差為:" + duration); // 將一個(gè)時(shí)間加上一定的分鐘數(shù) LocalTime time = LocalTime.of(9, 30); int minutesToAdd = 45; LocalTime newTime = time.plusMinutes(minutesToAdd); System.out.println("加上" + minutesToAdd + "分鐘后的時(shí)間為:" + newTime); // 將兩個(gè)時(shí)間相加 LocalTime time1 = LocalTime.of(10, 30); LocalTime time2 = LocalTime.of(0, 45); LocalTime sumTime = time1.plusHours(time2.getHour()).plusMinutes(time2.getMinute()); System.out.println("時(shí)間相加結(jié)果為:" + sumTime);
以上代碼中,首先使用LocalTime類創(chuàng)建了一些時(shí)間對(duì)象。LocalTime類是Java 8中新增的時(shí)間類,它可以表示時(shí)、分、秒和毫秒。接著,通過Duration類計(jì)算了兩個(gè)時(shí)間之間的差距,并輸出結(jié)果。然后,使用plusMinutes()方法將一個(gè)時(shí)間加上一定的分鐘數(shù),并輸出結(jié)果。最后,通過plusHours()和plusMinutes()方法將兩個(gè)時(shí)間相加,并輸出結(jié)果。