如何验证字符串到日历输入?

How to validate String to Calendar input?

这是我第一次在 Whosebug 上发帖。我需要一些帮助来验证从 String 到 Calendar 的用户输入。

例如,如果用户输入诸如“1”或 "hi" 之类的内容。我如何验证并提示用户输入 DDMMYYYY 格式的错误消息(类似于 04 02 2015)

System.out.print("Enter Date (DD MM YYYY): ");
          input.nextLine();
          String pickUpDate = input.nextLine();
          Calendar pd = stringToCalendarConverter(pickUpDate);

public static Calendar stringToCalendarConverter(String stringToCal) //Converts String to Calendar
{
   try 
   {
     DateFormat df = new SimpleDateFormat("dd MM yyyy"); 
     Date date = df.parse(stringToCal);
     Calendar calendar = new GregorianCalendar();
     calendar.setTime(date);  
     return calendar;
  }
  catch (ParseException n) 
  {
     return null;
  }      

}

调用 DateFormat.setLenient(boolean) 说(部分)严格解析,输入必须匹配此对象的格式。 类似于,

DateFormat df = new SimpleDateFormat("dd MM yyyy"); 
df.setLenient(false);

然后循环调用您的方法(重新提示 null 的日期)

Calendar pd = null;
while (pd == null) {
    System.out.print("Enter Date (DD MM YYYY): ");
    input.nextLine();
    String pickUpDate = input.nextLine();
    pd = stringToCalendarConverter(pickUpDate);
}
private static void dateConversion() {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter Date (DD MM YYYY): ");

    String pickUpDate = input.nextLine();        
    stringToCalendarConverter(pickUpDate);
}

public static void stringToCalendarConverter(String stringToCal) //Converts String to Calendar
{
    Calendar calendar = null;
    try {
        DateFormat df = new SimpleDateFormat("dd MM yyyy");
        df.setLenient(true);
        Date date = df.parse(stringToCal);
        calendar = new GregorianCalendar();
        calendar.setTime(date);

    } catch (ParseException n) {    // If the user entered incorrect format, it will be catch here.
        System.out.println("Invalid date format, pls try again.");
        dateConversion();           // Prompt the user to enter valid date.
    } finally{
        if(calendar != null){   
            showActualDate(calendar);
        }
    }
}

private static void showActualDate(Calendar cal){
    System.out.println("Entered ::::" +cal.getTime().toString());
}