tags:

views:

78

answers:

3

Hi everyone, to parse a string to a date sql valid:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");            
    java.util.Date date = null;
    try {
        date =  df.parse(dateimput);
    } catch (ParseException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

with dateimput is what i get from my form like that: String dateimput=request.getParameter("datepicker");
but when running see the error:

java.text.ParseException: Format.parseObject(String) failed
at java.text.Format.parseObject(Unknown Source)
at ServletEdition.doPost(ServletEdition.java:70)  

so it mean that dateimput is not known + I note that it is correctly dislayed when:

 System.out.println("datepicker:" +dateimput);

Thanks.

A: 

The "Unknown Error" error simply means your classpath doesn't contain the JDK sources and because of that it doesn't know where in Format's code the exception occurred (it does know to tell you what line in ServletEdition is problematic though).

abyx
A: 

This error happens because the input string to the parse method does not match what the pattern said it should look like:

public Date parse(String source) throws ParseException [...] Throws: ParseException - if the beginning of the specified string cannot be parsed.

See parse documentation.

So it seems, the input supplied in dateimput is invalid. As this may always happen with user input (I assume, that the value is actually user input...), it would be better to use, say, another version of parse, which allows you to determine where in the input string the parser had to punt, and does not require you to catch an exception in this case, but tells you about the failure using the result and the ParsePosition argument.

ParsePosition posn = new ParsePosition();
Date parsed = format.parse(input, posn);

if( parsed == null ) {

    int badPosn = posn.getErrorIndex();
    System.out.println("The input is invalid; the parser stopped at " + badPosn);

} else {

    // Do something with the date...
} 
Dirk
A: 

So It seems for the first time to be complicated but see carefully the solution. In fact we need 2 Simple Date Formater because tha parsing in my case will be done in 2 steps:

System.out.println("datepicker:" +dateimput);



    SimpleDateFormat df1 = new SimpleDateFormat("MM/dd/yyyy"); 
    SimpleDateFormat df2=new SimpleDateFormat("yyyy-MM-dd");
    Date dt=null;
    try {
        dt = df1.parse(dateimput);
        System.out.println("dt" +dt);
        System.out.println("dt formatted" +df2.format(dt));

    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

it works fine now and its ok

kawtousse