Search code examples
javadateambiguitydate-conversion

While converting String to Date got ambiguity between java.util.Date and java.sql.Date


I am trying to get date as input from Date tag of HTML

Birth Date <input type="date" name="dob"/>

and accessing on jsp page by using

String strDate = request.getParameter("dob");

but it returns in the format of string and I wanted to convert it in to date, I have tried as follows

SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(strDate);

But it gives error

incompatible types required: java.sql.Date found: java.util.Date

and when I imported pakage "java.util.*" for using java.util.Date date = sdf.parse(strDate); it gives

reference to Date is ambiguous, both class java.util.Date in java.util and class java.sql.Date in java.sql match


Solution

  • If you need a java.sql.Date (and incompatible types required: java.sql.Date found: java.util.Date indicates you do), remove the import of java.util.Date and use the java.util.Date returned by the DateFormat to construct a java.sql.Date with something like

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
        Date date = new Date(sdf.parse(strDate).getTime());
    } catch (ParseException e) {
        e.printStackTrace();
    }