I'm trying to convert a String to a Date variable in Java. To attempt to do so I'm trying a parse approach, which needs a try-catch block, but I'm having scope issues. The variable "date" in my Employee constructor isn't receiving the date, due to the date being in the try block. I receive the error: "date cannot be resolved to a variable". -- Please let me know your thoughts, or if I can convert the string to Date in an easier way. Thank you!
/Code Snippet/
String stringDate = sc.next();
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = dateFormatter.parse(stringDate);
}catch(ParseException e) {e.printStackTrace();}
e = new Employee(id, login, salary, date, name);
Employeeconstructor requires a date and you haven’t been able to obtain a date, then you can’t create the employee, neither should you want to.SimpleDateFormatandDate. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. If that’s a date of birth or a hire date, useLocalDatefrom java.time, the modern Java date and time API.Employeeobject inside thetrypart. Then it will only be created after successful parsing.LocalDatein a loop until a valid date is entered. Who can find such an example? It’s gotta be somewhere on Stack Overflow and/or elsewhere.