0

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.

4
  • Date date1 = dateformat.paste(sdate1); errors with 'Unhandled exception type ParseException' Printing date1 errors with 'The local variable date1 may not have been initialized'. Commented Aug 17, 2017 at 18:57
  • This happens because it maybe that dateformat.parse(sdate1) may throw and exception and assuming it does throw an exception, then the date1 variable will not be initialized and when you are trying to use that variable later on, it gives you the error. So, initialize date1 first: Date date1 = null; Commented Aug 17, 2017 at 19:00
  • this suggests that the variable is failing the Try. However, I cannot see how it could possibly fail: simple: if parse() throws an exception, date1 is not initialized, since parse() doesn't return anything, but throws instead. Commented Aug 17, 2017 at 19:04
  • I think i'm with you, so it throws this error just in case (so to speak), rather than analysing specifically what I have declared as the String variable and comparing it with the date format? Commented Aug 17, 2017 at 19:12

5 Answers 5

6

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Initializing to null first worked perfectly. What i'm struggling to understand though is how initializing the variable to null first allowed the value to pass through the try/catch? If the value was good enough to pass through, why would it need initializing?
@Tom Bennett You need to intializing cause compiler don't know will try block code generate exception or not and not provide any value to date1. Thats why compiler telling you that intialize the date1 incase try block code throw exception.
@TomBennett I believe the compiler’s message about "may not have been initialized" was a caution rather than an error. Your code was syntactically correct and would compile. Compilers and static code analyzers are trying to help with the quality as well as the correctness of your code. You were being warned that if that exception were thrown, your variable would never be assigned a value and would be unexpectedly null in code further down. Assigning null explicitly tells your IDE that you are aware of the situation and decided the possible null is acceptable, thereby silencing the caution.
3

All you have to do is initialize the variable, when you declare it:

Date date1 = null;

1 Comment

Some explanation/discussion would have helped this Answer.
3

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
}

Comments

3

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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.