Java DateTimeFormatter丢失分钟问题排查求助
Hey Nick, I see the problem here—your code is dropping minutes because the DateTimeFormatter you're using (or planning to use) doesn't include the minute component in its pattern. Let's break this down and fix it step by step.
Why the Minutes Are Getting Dropped
When parsing a time string like HH:MM with LocalTime.parse(), you need a formatter that explicitly accounts for both hours and minutes. If your formatter only specifies the hour pattern (like "HH" instead of "HH:mm"), the parser will either ignore the minutes part entirely or throw an error if the input doesn't match the expected pattern.
Corrected Code
Here's the full, fixed version of your code with proper time parsing that retains the minutes:
import java.util.Scanner; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class NewMain { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("\nDeparture time (HH:MM): "); String timeText = scanner.next(); // Define formatter to match the HH:MM input format DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm"); LocalTime time = LocalTime.parse(timeText, timeFormatter); // Verify minutes are preserved System.out.println("Parsed time: " + time); System.out.println("Extracted hours: " + time.getHour()); System.out.println("Extracted minutes: " + time.getMinute()); scanner.close(); } }
Key Details to Note
- The pattern
"HH:mm"tells the formatter to expect a 24-hour format hour (HH) followed by a colon and two-digit minutes (mm). If you need 12-hour format with AM/PM, use"hh:mm a"instead. scanner.next()works here because your input (HH:MM) has no spaces—if you ever need to read input with spaces, switch toscanner.nextLine()instead.- Always ensure the formatter's pattern exactly matches your input string structure. Mismatched patterns will either ignore parts of the input or throw a
DateTimeParseException.
Example Test Run
If you input 14:45, the output will be:
Departure time (HH:MM): 14:45 Parsed time: 14:45 Extracted hours: 14 Extracted minutes: 45
This confirms the minutes are correctly retained in the parsed LocalTime object.
内容的提问来源于stack exchange,提问作者Nick

