0

I want to change the String date from form data to java Date format as I'm passing it to a class and making an object of the class later for storing.

Here's my code

The form file

<hr>
    <label for="firstname"><b>First Name</b></label>
    <input type="text" placeholder="Enter First Name" name="FirstName" required>

    <label for="middlename"><b>Middle Name</b></label>
    <input type="text" placeholder="Enter Middle Name" name="MiddleName" required>

    <label for="lastname"><b>Last Name</b></label>
    <input type="text" placeholder="Enter Last Name" name="LastName" required>

    <label for="email"><b>Email</b></label>
    <input type="text" placeholder="Enter Email" name="Email" required>

    <label for="dob"><b>Enter Date of birth</b></label><br/>
    <input type="date" name="DOB" required><br/><br/>

The jsp redirected file

<%
        Employee obj = new Employee();
        obj.setFirstName(request.getParameter("FirstName"));
        obj.setMiddleName(request.getParameter("MiddleName"));
        obj.setLastName(request.getParameter("LastName"));
        //obj.setDob((String)request.getParameter("dob"));
        //**I wanna set the date here......**
        obj.setFirstName(request.getParameter("FirstName"));    
     %>

How can I go about through the problem. I'm currently building a Spring MVC web app.

Any suggestions or help are appreciated. Thank you for the same.

Siddhant Sahni
  • 157
  • 2
  • 13

3 Answers3

0

I think the simplest way is the best, try that:

Date date1 = new SimpleDateFormat("dd/MM/yyyy").parse((String)request.getParameter("dob")); 
Rafalsonn
  • 430
  • 7
  • 23
0

You should consider using Java's newer LocalDate and its parse method. Using it is quite well described in this article.

If you really need a Date you can get it from the resulting LocalDate:

Date date = Date.from(localDate.toInstant());
Michael
  • 2,443
  • 1
  • 21
  • 21
0

The generic solution for this would be to use Spring inbuilt annotation @InitBinder so that all the dates coming in complete controller will be automatically converted to the required format.You don't have to parse field by field manually.

@InitBinder
public final void initBinder(final WebDataBinder binder, final Locale locale) {
    final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", locale);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));    
}

Refer this thread to get more clarity on InitBinder.

https://stackoverflow.com/a/5211344/6572971

Alien
  • 15,141
  • 6
  • 37
  • 57