Reputation: 137
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.
Upvotes: 0
Views: 2473
Reputation: 1573
If you are not comfortable with a try catch, throw ParseException in your method declaration. Your code should work fine.
Upvotes: 3
Reputation: 1599
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.
Upvotes: 2
Reputation: 59986
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
}
Upvotes: 3
Reputation: 11845
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
}
Upvotes: 6
Reputation: 2476
All you have to do is initialize the variable, when you declare it:
Date date1 = null;
Upvotes: 3