2016-03-16 5 views
2

Я работаю в Java Swing, и мне нужно, чтобы получить году jYearChooser и месяц из jMonthChooser, а затем отформатировать его в этом формате «YYYY-MM-DD 00:00:00» Вот мой код, но он не дает ожидаемого результатаРабота с jYearChooser и jMonthChooser

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); 

, пожалуйста, помогите мне

+0

Что именно вы ожидаете и что такое выход? –

+0

Я выбираю 2016 год и год как месяц, но вывод - 3916-03-29 00:00:00 @AlexanderBaltasar –

ответ

2

это потому, что год параметр специфичен в конструкторе класса Date:

** 
* 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); 
} 

Также вы можете заметить, что этот конструктор @Deprecated. Поэтому лучше использовать 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()); 
+0

Большое вам спасибо @barsik, он отлично работал –