javasimpledateformatspaceparseexception

java use simpledateformat to parse a input String get ParseException, and just because of a space


I input a string likes the SimpleDateFormat pattern asked, but it will be ParseException. I do several tests. If I change space between "dd HH" to "dd-HH", the pattern becomes "yyyy-MM-dd-HH:mm:ss", and it will be successful. The second test is I write a string directly like String birthdays = "1998-08-12 12:12:12"; and parse it, it will also successful. so my conclusion is the space I input is not the same as the space in the pattern. what I used is IntelliJ.

        SimpleDateFormat datef = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input your birthday. the pattern is " +
                "yyyy-MM-dd HH:mm:ss");
        String birthday = sc.next();
        Date date2 = datef.parse(birthday);
//        String birthdays = "1998-08-12 12:12:12";
//        Date date2 = datef.parse(birthdays); //this will successful
        System.out.println(date2);

Solution

  • Instead of using sc.next() use sc.nextLine()

    sc.next() will find the first string till space but nextLine() will accept the entire string including space.

    That issue is not because of the space.