2

I'm working on a program that converts 24 hour time stamps into 12 hour time stamps. I managed to complete the conversion and loop it, but I need to code in an input validation that checks for incorrect inputs. An example of an incorrect input would be: "10:83" or "1):*2". Can someone show me how I can go about this using an Exception method? So far I have this:

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();       
    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
O Fakos
  • 35
  • 1
  • 2
  • 9
  • Some parse exception examples are found in the answers here: http://stackoverflow.com/questions/14563011/java-simpledateformat-unparseable-date-exception – mba12 Dec 02 '16 at 21:32
  • 2
    Please don’t use the long outmoded and notoriously troublesome `SimpleDateFormat` class. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 19 '17 at 11:18

4 Answers4

9

Use java.time the modern Java date and time API for this.

For a slightly lenient validation:

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

This will accept 09:41, 09:41:32 and even 09:41:32.46293846. But not 10:83, not 24:00 (should be 00:00) and not 9:00 (requires 09:00).

For stricter validation use an explicit formatter with the format you require:

    DateTimeFormatter strictTimeFormatter = DateTimeFormatter.ofPattern("HH:mm")
            .withResolverStyle(ResolverStyle.STRICT);

And pass it to the parsemethod:

        LocalTime.parse(inputTimeString, strictTimeFormatter);

Now also 09:41:32 gets rejected.

Question: Can I use java.time with my Java version?

If using at least Java 6, you can.

For learning to use java.time, see the Oracle tutorial or find other resoureces on the net.

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

You could use a regular expression to match the required time and throw an IllegalArgumentException?

if(! input1.matches("(?:[0-1][0-9]|2[0-4]):[0-5]\\d")){
      throw new IllegalArgumentException("The time you entered was not valid");
    }
saml
  • 794
  • 1
  • 9
  • 20
  • the regex above wont work with 24:00 (which could be a valid time) this one worked for me if(!input1.matches("([01]\\d|2[0-3]):[0-5]\\d")) – e.f.a. Oct 28 '21 at 17:39
0
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);
} 
abdessamed
  • 11
  • 4
0

This function checks only format 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;
    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
RED-ONE
  • 167
  • 1
  • 5