简体   繁体   中英

Test the time format HH:MM:SS.sss

So I'm writing a code that tests to see if an input is in the right time format of HH:MM:SS.sss, to check it properly I run four different inputs, three that should return false and one that should return True, but for some reason when I input the correct format I get an "Java.text.ParseExcetion data: "02:26:13.125"" and it returns false. what am i doing wrong or missing? here is my code

public static boolean checkTradeTimeFmt(String trade_time){
        if (trade_time == null)
            return false;

        //set the format to use as a constructor argument
        SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss.sss");

        if (trade_time.trim().length() != dateFormat.toPattern().length())
            return false;

        dateFormat.setLenient(false);

        try {
            //parse the trade_time parameter
            dateFormat.parse(trade_time.trim());
        }
        catch (ParseException pe) {
            return false;
        }
        return true;
    }

In your date pattern, the milliseconds need to be specified using upper-case "SSS":

    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss.SSS");

Also, note that using lower-case "hh" implies that the hour is expressed as 1 - 12 (12-hour clock). If the hour is expressed as 0 - 23 (24-hour clock), you need to use upper case "HH".

Modern answer:

LocalTime.parse(trade_time);

This uses DateTimeFormatter.ISO_LOCAL_TIME , which matches your requred format except that it also accepts longer and shorter formats, for example 02:26 and 02:26:13.123456789 . Maybe you can live with it. DateTimeFormatter.ISO_LOCAL_TIME uses strict resolving, so will throw a DateTimeFormatException if any field is out of range.

If you cannot live with longer or shorter formats being accepted, build your own DateTimeFormatter . Its patterns are much like SimpleDateFormat 's.

    DateTimeFormatter timeParseFormatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS")
                                            .withResolverStyle(ResolverStyle.STRICT);
    LocalTime.parse(trade_time, timeParseFormatter);

This will require exactly 3 decimals on the seconds and will throw a DateTimeParseException if there are either 2 or 4 decimals, for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM