【问题标题】:How to check if time format is correct in Java (with Exception)如何检查 Java 中的时间格式是否正确(有异常)
【发布时间】:2017-04-17 21:11:02
【问题描述】:

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

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();       
    }
}

【问题讨论】:

标签: java time time-format


【解决方案1】:

这个函数只检查格式 hh:mm

public static boolean isTimeValid(String value) {
    try {
        String[] time = value.split(":");
        return  Integer.parseInt(time[0]) < 24 && Integer.parseInt(time[1]) < 60;
    } catch (Exception e) {
        return false;
    }
}

【讨论】:

  • 拒绝10:83 好吧。接受1:3010:03821:3:p.m.:some:text
【解决方案2】:

您可以使用正则表达式来匹配所需时间并抛出 IllegalArgumentException?

if(! input1.matches("(?:[0-1][0-9]|2[0-4]):[0-5]\\d")){
      throw new IllegalArgumentException("The time you entered was not valid");
    }

【讨论】:

  • 上面的正则表达式不适用于 24:00(这可能是一个有效时间)这个对我有用 if(!input1.matches("([01]\\d|2[0- 3]):[0-5]\\d"))
【解决方案3】:
String inputTimeString = "10:83";
if (!inputTimeString.matches("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$")){
     System.out.println("Invalid time string: " + inputTimeString);
} 

【讨论】:

    【解决方案4】:

    为此使用 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);
        }
    

    这将接受 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);
    

    并将其传递给parse方法:

            LocalTime.parse(inputTimeString, strictTimeFormatter);
    

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 2015-06-22
      • 2015-02-10
      • 1970-01-01
      相关资源
      最近更新 更多