LGoodDatePicker issues with getDate()

I’m using the LGoodDatePicker with Apache NetbeansIDE 12.2 (https://github.com/LGoodDatePicker/LGoodDatePicker), and I need to get the date in the format YYYY-MM-DD. I’m using this code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(datePicker1.getDate());

But I get this error:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot format given Object as a Date

Any suggestions? Thank you.

Answer

The method getDate() of this DatePicker returns a java.time.LocalDate, not a java.util.Date. That’s actually what the error message tells you, it expects a java.util.Date but got something else.
That means you shouldn’t try to format it using a java.text.SimpleDateFormat, use a java.time.format.DateTimeFormatter here:

String date = datePicker1.getDate().format(DateTimeFormatter.ISO_LOCAL_DATE);

or define a custom pattern using the method ofPattern(String pattern) of the DateTimeFormatter:

String date = datePicker1.getDate().format(DateTimeFormatter.ofPattern("uuuu-MM-dd");

In this very case, you can even use the toString() method of the LocalDate in order to get a String in the desired format:

String date = datePicker1.getDate().toString();

Leave a Reply

Your email address will not be published. Required fields are marked *