0

I am new to JFrame. I just started learning about creating a Java project. I created an input field as a date and inserted a DateChooseCombo. I have 2 problems.

  1. When I run the application dates in the calendar are invisible but, it shows the date which is selected in the box.
  2. When I submit the form it gives an error as "Cannot format given Object as a Date"

The code for the date is as follows:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String addDate = dateFormat.format(txt_AddDate.getSelectedDate());
ps.setString(3 ,addDate);

The date format used is 04/30/2021.

Can anyone help me to solve these two problems?

  • 3
    If you post a [mre] that we can copy into our IDE and test, then you're more likely to get help. Without seeing the code, we can't tell what you did. – Gilbert Le Blanc May 01 '21 at 06:26
  • 1
    The IDE is irrelevant to the problem (unless the code works OK in another IDE). Don't tag it or mention it in the title. – Andrew Thompson May 01 '21 at 08:54
  • 1
    If the date format is is 04/30/21, why are you specifying format MM/dd/yyyy, which is for 04/30/2021? – Mark Rotteveel May 01 '21 at 10:15
  • 1
    Two recommendations: (1) Don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Date pickers exist that support `LocalDate` *and* Swing. (2) Don’t pass the selected date as a string to your prepared statement. Pass a `LocalDate`. See [Insert & fetch …](https://stackoverflow.com/questions/43039614/insert-fetch-java-time-localdate-objects-to-from-an-sql-database-such-as-h2). – Ole V.V. May 01 '21 at 12:09

1 Answers1

1

Method getSelectedDate(), in class datechooser.beans.DateChooserCombo, returns a java.util.Calendar.

Method format, in class java.text.DateFormat (which is superclass of java.text.SimpleDateFormat and hence inherited by SimpleDateformat) requires a parameter of type java.util.Date. A Calendar is not a Date and that's why you are getting the error. Java cannot convert a Calendar to a Date.

However, class Calendar has method getTime which returns a Date.
So you need to change the second line of the code, that you posted in your question, to the following.

String addDate = dateFormat.format(txt_AddDate.getSelectedDate().getTime());

You can also refer to the following question (and answer) :
Can't get date from DateChooserCombo

Abra
  • 19,142
  • 7
  • 29
  • 41