将String转换为日历时出错?

时间:2014-12-08 09:25:49

标签: java eclipse calendar simpledateformat parseexception

我想在字符串中获取客户端的到达日期并将其作为参数传递给strToCal方法,此方法返回具有该日期的Calendar对象,但它不起作用,id得到解析异常错误:

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

1 个答案:

答案 0 :(得分:2)

sc.next()替换为sc.nextLine();

因为sc.next()将在第一个空格中拆分,而您的输入字符串不会是正确的模式。

修改我已尝试过此代码:

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

next()

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

nextLine()

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