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

时间:2015-02-04 05:37:14

标签: java string validation calendar

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

例如,如果用户输入诸如" 1"或者"嗨"。我如何验证并提示用户输入DDMMYYYY格式的错误消息(类似于2015年02月02日)

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

}

2 个答案:

答案 0 :(得分:1)

使用严格的解析调用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);
}

答案 1 :(得分:0)

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