Search code examples
javamysqlhibernatespring-mvcdate-parsing

How to convert String to java.util.date so as to make it insertable to the mysql database column of type "DATE"?


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 class java.util.Date

The user inputs the date like this: Date Input

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"

Solution

  • The specific error in this case is the wrong date format. Instead of MM/dd/yyyy you should use yyyy-MM-dd in order to parse the date.

    If the date cannot be parsed null is inserted in the database and that is ok. This means that the format of the date is wrong.

    Here is a snippet of code which should work be able to parse the date:

    String startDateParser = "2018-04-19";
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date finalStartDate = null;
    try {
        finalStartDate = format.parse(startDateParser);
        System.out.println(finalStartDate);
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
    }