如何使用Java LocalTime API处理超24小时时间格式(如25:15:00转01:15:00)
解决超过24小时的时间格式转换问题
LocalTime API仅支持表示00:00到23:59:59的单日时间,直接解析25:15:00这类超24小时的字符串会触发DateTimeParseException。以下是两种可行的转换方案:
方案一:手动拆分计算
直接拆分时间字符串,对小时数取模24后构建LocalTime:
public static LocalTime normalizeOver24hTime(String timeStr) { String[] timeParts = timeStr.split(":"); int rawHours = Integer.parseInt(timeParts[0]); int minutes = Integer.parseInt(timeParts[1]); int seconds = Integer.parseInt(timeParts[2]); int normalizedHours = rawHours % 24; return LocalTime.of(normalizedHours, minutes, seconds); } // 使用示例 String inputTime = "25:15:00"; LocalTime convertedTime = normalizeOver24hTime(inputTime); System.out.println(convertedTime); // 输出:01:15:00
方案二:借助Duration类处理
将时间转换为总时长后,取模单日时长(24小时),再转成LocalTime:
public static LocalTime normalizeWithDuration(String timeStr) { String[] timeParts = timeStr.split(":"); long totalSeconds = Integer.parseInt(timeParts[0]) * 3600L + Integer.parseInt(timeParts[1]) * 60L + Integer.parseInt(timeParts[2]); Duration totalDuration = Duration.ofSeconds(totalSeconds); Duration dailyDuration = Duration.ofHours(24); Duration normalizedDuration = totalDuration.minus(dailyDuration.multipliedBy(totalDuration.toHours() / 24)); return LocalTime.MIN.plus(normalizedDuration); } // 使用示例 String inputTime = "25:15:00"; LocalTime convertedTime = normalizeWithDuration(inputTime); System.out.println(convertedTime); // 输出:01:15:00
两种方案都能处理诸如48:00:00→00:00:00、73:30:45→01:30:45这类边界场景。
内容的提问来源于stack exchange,提问作者Arushi
相关产品推荐
相关产品推荐

