2

i'm working in java swing and i need to get year a jYearChooser and month from a jMonthChooser and then format it to this format "yyyy-MM-dd 00:00:00" Here is my code , but it doesn't give the expected output

int year = jYearChooser1.getYear();
int month = jMonthChooser1.getMonth();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
Date dt = new Date(year, month,00);
Date todate = dateFormat.format(dt);

please help me

1 Answers1

2

That's because year parameter is specific in Date class constructor:

**
 * Allocates a <code>Date</code> object and initializes it so that
 * it represents midnight, local time, at the beginning of the day
 * specified by the <code>year</code>, <code>month</code>, and
 * <code>date</code> arguments.
 *
 * @param   year    the year minus 1900.
 * @param   month   the month between 0-11.
 * @param   date    the day of the month between 1-31.
 * @see     java.util.Calendar
 * @deprecated As of JDK version 1.1,
 * replaced by <code>Calendar.set(year + 1900, month, date)</code>
 * or <code>GregorianCalendar(year + 1900, month, date)</code>.
 */
@Deprecated
public Date(int year, int month, int date) {
    this(year, month, date, 0, 0, 0);
}

Also you can notice that this constructor is @Deprecated. So better idea is to use Calendar:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");

Calendar c = Calendar.getInstance();
c.set(year, month, 1); // Specify day of month

String formattedDate = dateFormat.format(c.getTime());
Ιναη ßαbαηιη
  • 3,410
  • 3
  • 20
  • 41