0

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;
    }
Gonzo3207
  • 9
  • 1
  • 2
  • That’s `hh` for hour in the range 1–12, capital `HH` for hour 0–23. The former is meant for use with AM/PM. – Ole V.V. May 18 '17 at 07:55
  • Possible duplicate of [How to sanity check a date in java](http://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java) – Ole V.V. May 18 '17 at 07:56

2 Answers2

2

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".

Phil Grigsby
  • 271
  • 2
  • 4
  • i was wondering why i was seeing some cases where its capitalized or not, thanks!!! totally working now – Gonzo3207 May 18 '17 at 02:14
0

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161