如何用Java计算两个时间的总和?代码异常排查求助
Hey Michael, let's break down why your time sum is spitting out negative values and inaccurate results, then fix it properly.
The Root of the Problem
Chances are you're making one of two common mistakes:
- Confusing time points with durations: If you're adding the timestamp values (like
Date.getTime()orLocalTime.toSecondOfDay()) directly, you're treating "23:00" as a point in time, not a length of time. This leads to overflow or wrapping around the 24-hour clock (e.g., 23h + 2h gets truncated to 1h instead of 25h). - Using integer overflow: If you're storing seconds/hours in
intvariables instead oflong, large values can wrap into negative numbers (sinceinthas a max value of ~2 billion, which is only about 23 days of seconds).
The Correct Approach: Use Durations
Java 8+ gives us the Duration class, which is designed specifically to represent lengths of time. We'll convert each input time to a duration (relative to midnight), add them, then format the total into a readable format.
Here's a working implementation:
import java.time.Duration; import java.time.LocalTime; public class TimeSumCalculator { public static void main(String[] args) { // Example input times (replace these with your actual values) LocalTime time1 = LocalTime.of(23, 30, 15); // 23h 30m 15s LocalTime time2 = LocalTime.of(2, 45, 30); // 2h 45m 30s // Convert each time to a duration from midnight Duration duration1 = Duration.between(LocalTime.MIDNIGHT, time1); Duration duration2 = Duration.between(LocalTime.MIDNIGHT, time2); // Safely add the two durations Duration totalDuration = duration1.plus(duration2); // Format the total duration into a human-readable format long totalHours = totalDuration.toHours(); long remainingMinutes = totalDuration.toMinutes() % 60; long remainingSeconds = totalDuration.getSeconds() % 60; System.out.printf("Total time: %d:%02d:%02d%n", totalHours, remainingMinutes, remainingSeconds); // Or split into days + hours if needed: long days = totalDuration.toDays(); long hours = totalDuration.toHours() % 24; System.out.printf("Total time (with days): %d days, %d:%02d:%02d%n", days, hours, remainingMinutes, remainingSeconds); } }
What This Code Does
Duration.between(LocalTime.MIDNIGHT, timeX): Converts your input time (e.g., 23:30) into a duration representing how much time has passed since midnight (23.5 hours).duration1.plus(duration2): Adds the two durations without overflow (sinceDurationuseslonginternally to store values).- The formatting steps let you display the total as a single "over-24-hour" time (like 26:15:45) or split into days + hours for clarity.
If You're Stuck With Legacy Java (Pre-8)
If you can't use Java 8+, you can manually calculate the total seconds using long to avoid overflow:
public class LegacyTimeSum { public static void main(String[] args) { // Example times: hours, minutes, seconds int t1Hours = 23, t1Mins = 30, t1Secs = 15; int t2Hours = 2, t2Mins = 45, t2Secs = 30; // Calculate total seconds using long to prevent overflow long totalSeconds = (long)t1Hours * 3600 + t1Mins * 60 + t1Secs + (long)t2Hours * 3600 + t2Mins * 60 + t2Secs; // Convert back to hours, minutes, seconds long totalHours = totalSeconds / 3600; long remainingMins = (totalSeconds % 3600) / 60; long remainingSecs = totalSeconds % 60; System.out.printf("Total time: %d:%02d:%02d%n", totalHours, remainingMins, remainingSecs); } }
关键要记住:你要计算的是时长的总和,不是两个时间点相加得到的新时间点。这是很多人容易混淆的概念!
内容的提问来源于stack exchange,提问作者Michael1
相关产品推荐
相关产品推荐

