Search code examples
jspdaterequestsimpledateformat

converting request.getparameter() result to date


I have a jsp page which takes an input type date. In the servlet am using request.getParameter() and SimpleDateFormat to get the date which the user has input.

My problem is i only want to get the day, month and year but i also get the time, meaning when i display back the date i display in this format- Day Name : Month: Day of Month : Time : Year, but i only want to display - Year : Month : Day of Month.

Here is what i have done :

Date startDate=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("startDate")); //get the parameter convert it to a data type Date.

out.println(startDate); //Display the date

What seems to be the problem here?

Thank you for your time.


Solution

  • Your problem is you are passing Date (java.util.Date) object to println method. println internally calls Date#toString() on the date object, which results in the format that you don't want.

    Solution

    If your problem is within servlet you want Date object then

    String startDateStr = request.getParameter("startDate");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //surround below line with try catch block as below code throws checked exception
    Date startDate = sdf.parse(startDateStr);
    //do further processing with Date object
    ......
    .... 
    

    If you want to print the date then you can convert the date to String according to your format and pass that string to println method

    out.println(sdf.format(startDate)); //this is what you want yyyy-MM-dd  
    

    See also