SimpleDateFormat,不允许超过12小时 [英] SimpleDateFormat and not allowing it to go above 12 hours

查看:255
本文介绍了SimpleDateFormat,不允许超过12小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想扩展此方法,以使用户输入有效的12小时时间.我对此表示满意,可以.但是我想要这样,如果小时超过12小时或分钟超过59,那么它将提示您再次执行此操作.但是现在,它只是通过添加时间来转换时间. 还有写这个的更有效的方法吗? (就像没有 日期newTime = sdf.parse(startTime); 是否具有它,以便用户可以输入字符串并检查其格式是否正确?

So I have this method that I wanted to expand on to have the user input a valid 12 hour time. And I have it to this which works okay. But I want it so that if the hour is over 12 hours or the minutes is over 59 then it will prompt to do it again. But right now it will just convert the time by adding it. Also is there a more efficient way to write this? (Like without having the Date newTime = sdf.parse(startTime); And have it so that the user can just input a string and have it check if it's in the correct format?

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

推荐答案

您遇到的SimpleDateFormat行为符合设计要求.对于大多数人来说,这是一种负面的惊喜.

You are experiencing SimpleDateFormat behaving as designed. It’s a behaviour that comes as a negative surprise to most.

有两种解决方案:推荐的一种和灰心的一种.

There are two solutions: the recommended one and the discouraged one.

推荐的解决方案:LocalTime

        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的经验).

LocalTime and a bunch of other better designed and more programmer-friendly classes were introduced in Java 8. If you cannot use Java 8, there are again two solutions: (1) Resort to the discouraged solution, see below. (2) Use the backport of the Java 8 date and time classes to Java 6 and 7: ThreeTen Backport (I haven’t got experience with ThreeTen Backport).

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

In the code, please specify the correct locale instead of Locale.ROOT. I don’t know whether AM and PM may have other names in some locales, so I would want to make sure we are using a locale that agrees with the user input on this point.

不利的解决方案:setLenient()

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

SimpleDateFormat默认为宽容,接受09:63为10:03和14:00 AM为02:00 PM.当您setLenient(false)时,它将不再以这种方式接受超出范围的值,而是将按您的预期抛出ParseException.

The SimpleDateFormat is lenient as default and accepts 09:63 as 10:03 and 14:00 AM as 02:00 PM. When you setLenient(false), it will no longer accept out-of-range values this way, but will throw a ParseException as you had expected.

只需检查格式是否正确

在任何一种解决方案中,检查格式的最佳方法是正在执行的操作:尝试解析它并捕获相关的异常类型.请特别注意,不要只捕获Exception,因为异常可能是由许多其他原因引起的.也就是说,使用推荐的解决方案捕获DateTimeParseException,使用不推荐的解决方案捕获ParseException.

In either solution, the best way to check the format is what you are already doing: you try to parse it and catch the relevant exception type. Only don’t just catch Exception, be specific since exceptions may come of many other causes. That is, catch DateTimeParseException with the recommended solution and ParseException with the discouraged solution.

此外,如果您想存储以后使用的时间,将其存储为LocalTime(或哪种类最能反映您的需求)而不是String可能更方便且面向对象.

Also, if you want to store the time for use later, it is probably more convenient and object-oriented to store it as a LocalTime (or what class best reflects your needs) rather than String.

这篇关于SimpleDateFormat,不允许超过12小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆