Search code examples
javaeclipsecalendarsimpledateformatparseexception

error in converting String to Calendar?


i want to get arrival date of a client in string and pass it as a parameter to strToCal method,this method returns an Calendar object with that date,but it wouldn't work,id get parse exception error:

static String pattern = "yyyy-MM-dd HH:mm:ss";
System.out.println("enter arrival date ("+ pattern +"):\n" );
c.setArrDate(strToCal(sc.next(),c));
System.out.println("enter departure date ("+ pattern +"):\n");
c.setResTilDate(strToCal(sc.next(),c));

static Calendar strToCal(String s, Client c) throws ParseException {
    try{
        DateFormat df = new SimpleDateFormat(pattern);
        Calendar cal  = Calendar.getInstance();
        cal.setTime(df.parse(s));
        return cal;
    } catch(ParseException e){
        System.out.println("somethings wrong");
        return null;
    }

Solution

  • Replace sc.next() with sc.nextLine();

    because sc.next() will split on the first space and your input string won't be of the correct pattern.

    Edit I've tried this code:

    public class Test4 {
        static String pattern = "yyyy-MM-dd HH:mm:ss";
    
        public static void main(String[] args) {
            Calendar c = Calendar.getInstance();
            final Scanner input = new Scanner(System.in);
            System.out.println("input date: ");
            String a = input.nextLine();
            c = strToCal(a);
            System.out.println(c.getTime());
        }
    
    
        static Calendar strToCal(String s) {
            try {
                DateFormat df = new SimpleDateFormat(pattern);
                Calendar cal = Calendar.getInstance();
                cal.setTime(df.parse(s));
                return cal;
            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    

    with next():

    input date:
    2014-05-16 13:30:00
    java.text.ParseException: Unparseable date: "2014-05-16"
            at java.text.DateFormat.parse(Unknown Source)
    

    with nextLine():

    input date:
    2014-05-16 13:30:00
    Fri May 16 13:30:00 EEST 2014