javadatejava.util.datejava.util.calendar

Why I obtain this error when I try to build a Java.utile.Date object from a String?


I am working on a Java application and I have some problem trying to create a Date object:

So I have done:

Calendar dataRendimentoLordoCertificatoCalendar = Calendar.getInstance();
dataRendimentoLordoCertificatoCalendar.set(annoCorrente - 1, 10, 01);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dataRendimentoLordoCertifiacato = new Date(sdf.format(dataRendimentoLordoCertificatoCalendar.getTime()));

Using the Eclipse debugger I can see that the value of sdf.format(dataRendimentoLordoCertificatoCalendar.getTime()) (passed as parameter to the Date constructor) is 2015-11-01 (and it is what I expect: the first of November of 2015).

The problem is that when this line is performed:

Date dataRendimentoLordoCertifiacato = new Date(sdf.format(dataRendimentoLordoCertificatoCalendar.getTime()));

I obtain this exception:

Exception in thread "main" java.lang.IllegalArgumentException
    at java.util.Date.parse(Date.java:598)
    at java.util.Date.<init>(Date.java:255)
    at com.mycompany.dbmanager.MyProject.getRendimentoLordoCertificato(PucManager.java:64)

How can I fix this issue?


Solution

  • I don't know why you want this solution, but if you want to use String (returned type of getTime), you have to use parse, like this:

    public static void main(String[] args) throws ParseException {
      Calendar dataRendimentoLordoCertificatoCalendar = Calendar.getInstance();
    
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      Date dataRendimentoLordoCertifiacato = sdf.parse(sdf.format(dataRendimentoLordoCertificatoCalendar.getTime()));
    
      System.out.println(dataRendimentoLordoCertifiacato);
    }
    

    But, I don't know what exactly you want. Because you have a DATE, then you are gettin String of this date and then you parse it back to date :-D