You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java DateTimeFormatter丢失分钟问题排查求助

Fixing the Issue of Missing Minutes in Time Parsing

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 to scanner.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:53:59