The user inputs a date as a string
, but I need to make that insertable to the database column of datatype DATE
. This is how I've defined my startDate
variable in my Event.java
class:
@Column(name = "start_date")
@Temporal(javax.persistence.TemporalType.DATE)
private Date startDate;
Note: The
Date
datatype is from the classjava.util.Date
The user inputs the date like this:
I fetch that data as a string value with the following bit of code in my controller:
@RequestMapping(value = "/addEvent", method = RequestMethod.POST)
public String addEvent(
//OTHER PARAMETERS
@RequestParam("startDate") String startDate,
//OTHER PARAMETERS
) {
//CODE TO MAP EVENT DATA TO THE ENTITY CLASS
eventDAO.insert(event);
return "redirect:/";
}
The above code successfully inserts an event to the database but leaves the start_date
column NULL
. How do I parse the string value to a date
datatype so as to be insertable into the MySQL DB?
EDIT:
I tried adding the following to parse it but it still inserts NULL
.
Date finalStartDate=null;
String startDateParser = startDate;
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try{
finalStartDate = format.parse(startDateParser);
System.out.println(finalStartDate);
} catch(ParseException ex){
System.out.println(ex.getMessage());
}
Event event = new Event();
//MAPPING OTHER DATA
event.setStartDate(finalStartDate);
I got this message in my server:
Unparseable date: "2018-04-19"