【问题标题】:SimpleDateFormat and not allowing it to go above 12 hours [closed]SimpleDateFormat 并且不允许它超过 12 小时 [关闭]
【发布时间】:2017-08-27 04:27:40
【问题描述】:

所以我想扩展这个方法,让用户输入一个有效的 12 小时时间。我有它,它工作正常。但我想要它,如果小时超过 12 小时或分钟超过 59,那么它会提示再次执行此操作。但现在它只会通过添加时间来转换时间。 还有更有效的方法来写这个吗? (就像没有 Date newTime = sdf.parse(startTime); 让用户只需输入一个字符串并让它检查它的格式是否正确?

public static void userInput(){
    Scanner in = new Scanner(System.in);
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
    String startTime;

    System.out.print("What is the start time?: ");
    boolean success = false;
    while (success != true){
        try{
        startTime = in.nextLine();
        Date newTime = sdf.parse(startTime);
        startTime = sdf.format(newTime);


        System.out.println(startTime);

        success = true;
        }
        catch(Exception e){
            System.out.println("Not a valid time. Please use this format (HH:MM AM)");
        }
    }
}

【问题讨论】:

  • DateSimpleDateFormat 现在是旧版,被 java.time 类取代(巨大改进)。

标签: java date time format simpledateformat


【解决方案1】:

您正在体验SimpleDateFormat 的设计行为。这种行为让大多数人感到意外。

有两种解决方案:推荐的一种和不鼓励的一种。

推荐解决方案:本地时间

        DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("hh:mm a", Locale.ROOT);
        try {
            LocalTime lt = LocalTime.parse(startTime, timeFormat);
            startTime = lt.format(timeFormat);
            System.out.println(startTime);
        } catch (DateTimeParseException e) {
            System.out.println("Not a valid time. Please use this format (HH:MM AM)");
        }

LocalTime 和一堆其他设计更好、对程序员更友好的类在 Java 8 中引入。如果你不能使用 Java 8,还有两个解决方案:(1)求助于不鼓励的解决方案,见下文。 (2) 使用 Java 8 日期和时间类的 backport 到 Java 6 和 7:ThreeTen Backport(我没有使用 ThreeTen Backport 的经验)。

在代码中,请指定正确的语言环境而不是Locale.ROOT。我不知道 AM 和 PM 在某些语言环境中是否可能有其他名称,所以我想确保我们使用的语言环境与用户在这一点上的输入一致。

不鼓励的解决方案:setLenient()

    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
    sdf.setLenient(false);

SimpleDateFormat 默认是 lenient 并且接受 09:63 作为 10:03 和 14:00 AM 作为 02:00 PM。当您setLenient(false) 时,它将不再以这种方式接受超出范围的值,而是会像您预期的那样抛出ParseException

只是检查格式是否正确

在任一解决方案中,检查格式的最佳方法是您已经在做的事情:您尝试解析它并捕获相关的异常类型。只是不要只捕获Exception,因为异常可能来自许多其他原因。也就是说,使用推荐的解决方案捕获DateTimeParseException,使用不推荐的解决方案捕获ParseException

另外,如果您想存储时间以供以后使用,将其存储为LocalTime(或最能反映您的需求的类)可能比String 更方便且面向对象。

【讨论】:

    猜你喜欢
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多