简体   繁体   中英

Unable to convert String to Date

I'm unable to convert a String to a Date in Java and I just can't figure it out.

String sdate1 = "01/04/2016";
SimpleDateFormat  dateformat = new SimpleDateFormat("dd/MM/yyyy");  
Date date1 = dateformat.parse(sdate1);

The last line causes an error, which forces me to surround it with a try/catch.

Surrounding this with a try/catch then causes the date1 to cause an error later on when trying to print the variable. The error states 'The local variable date1 may not have been initialized'.

Date date1;
try {
    date1 = dateformat.parse(sdate1);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

From some digging on the internet, I think that this suggests that the variable is failing the try. However, I cannot see how it could possibly fail.

date1 variable is not definitely assigned in your case (it will not get any value if an exception is thrown as catch clause does not assign any value to the variable), so you cannot use it later (for example, to print).

To fix this, you could give the variable some initial value:

Date date1 = null;
try {
    date1 = dateformat.parse(sdate1);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
if (date1 != null) {
    // it was parsed successfully
    .. do something with it
}

您需要做的就是在声明变量时初始化变量:

Date date1 = null;

You try to use the date after the try/catch which mean you use it in different scope of the try block for that you get this error, to solve this problem you have to initialize the date for example :

private Date useDate() {
    String sdate1 = "01/04/2016";
    SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
    Date date1 = null;//<<------------------initialize it by null
    try {
        date1 = dateformat.parse(sdate1);
    } catch (ParseException ex) {
        //throw the exception
    }
    return date1;//<<--------if the parse operation success 
                 //          then return the correct date else it will return null
}

If you are not comfortable with a try catch, throw ParseException in your method declaration. Your code should work fine.

You can init your date1 = null or move it inside the try/catch.

        String sdate1 = "01/04/2016";
        SimpleDateFormat  dateformat = new SimpleDateFormat("dd/MM/yyyy");  
        try {
            Date date1 = dateformat.parse(sdate1);
            System.out.println(date1);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM