如何检查 Java 中的时间格式是否正确(有异常)

O F*_*kos 1 java time time-format

我正在开发一个将 24 小时时间戳转换为 12 小时时间戳的程序。我设法完成转换并循环它,但我需要在检查不正确输入的输入验证中编码。错误输入的示例是:“10:83”或“1):*2”。有人可以告诉我如何使用 Exception 方法来解决这个问题吗?到目前为止,我有这个:

public class conversion {

        public static void timeChange() throws Exception {
            System.out.println("Enter time in 24hr format");
            Scanner sc = new Scanner(System.in);
            String input1 = sc.nextLine();
            DateFormat df = new SimpleDateFormat("HH:mm");
            DateFormat df2 = new SimpleDateFormat ("hh:mm a");
            Date date = null;
            String timeOutput = null;

            date = df.parse(input1);
            timeOutput = df2.format(date);

            System.out.println("in 12 hour format: " + timeOutput);

            decision();
        }

        public static void decision() throws Exception {
            System.out.println("Would you like to enter another time?");

            Scanner sc2 = new Scanner(System.in);
            String userChoice = sc2.nextLine();

            while (userChoice.equalsIgnoreCase("Y")) {
                timeChange();
            }
            System.exit(0);
        }

        public static void main(String[] args) throws Exception {
            timeChange();       
    }
}
Run Code Online (Sandbox Code Playgroud)

Ole*_*.V. 6

java.time为此使用现代 Java 日期和时间 API。

对于稍微宽松的验证:

    String inputTimeString = "10:83";
    try {
        LocalTime.parse(inputTimeString);
        System.out.println("Valid time string: " + inputTimeString);
    } catch (DateTimeParseException | NullPointerException e) {
        System.out.println("Invalid time string: " + inputTimeString);
    }
Run Code Online (Sandbox Code Playgroud)

这将接受 09:41、09:41:32 甚至 09:41:32.46293846。但不是 10:83,不是 24:00(应该是 00:00),也不是 9:00(需要 09:00)。

要进行更严格的验证,请使用具有所需格式的显式格式化程序:

    DateTimeFormatter strictTimeFormatter = DateTimeFormatter.ofPattern("HH:mm")
            .withResolverStyle(ResolverStyle.STRICT);
Run Code Online (Sandbox Code Playgroud)

并将其传递给parse方法:

        LocalTime.parse(inputTimeString, strictTimeFormatter);
Run Code Online (Sandbox Code Playgroud)

现在 09:41:32 也被拒绝了。

问:我可以使用java.time我的 Java 版本吗?

如果至少使用 Java 6,则可以。

要学习使用java.time,请参阅Oracle 教程或在网上查找其他资源。