2017-03-08 44 views
0

我已將年,月,日分開放置JComboBoxes月份JComboBox自己的renderer可顯示月份名稱而不是月份的integer值。在哪裏月開始於0 (0-January....11-December)將JComboBox年,月,日整數值連接或格式化爲日期類型

因此,我的問題是如何將年,月,日放在一起並將其分配給Date數據類型。

我試圖串聯年,月,日一起到String可變

int startYear = Integer.parseInt(jcmbFirstSemStartDateYear.getSelectedItem().toString()); 
int startMonth = Integer.parseInt(jcmbFirstSemStartDateMonth.getSelectedItem().toString()); 
int startDay = Integer.parseInt(jcmbFirstSemStartDateDay.getSelectedItem().toString()); 

String startDate = startYear+"-"+startMonth+"-"+startDay; //not sure if this okay 
Date completeStartDate = java.sql.Date.valueOf(startDate); 
JOptionPane.showMessageDialog(null,completeStartDate); 

hasConflict(completeStartDate, completeEndDate); //method to check conflict 

但是當我打印的completeStartDate值時,它顯示二月份爲01

enter image description here

我擔心這可能會被讀爲1月份,而不是2月份,當我提取月份來檢查衝突。

public static boolean hasConflict(Date aStartDate, Date aEndDate){ 
     boolean hasConflict = false; 
     Calendar calStart = Calendar.getInstance(); 
     calStart.setTime(aStartDate); 
     int startYear = calStart.get(Calendar.YEAR); 
     int startMonth = calStart.get(Calendar.MONTH); //extract month 
     int startDay = calStart.get(Calendar.DAY_OF_MONTH); 
     // ... if else conditions to compare startDate with endDate 
     return hasConflict; 
    } 

後來,我將這些日期存儲到mysql數據庫。

任何想法或建議?

謝謝。

+0

你可以創建一個String表示然後根據格式解析它,或者你可以使用['LocalDate.of(year,month,dayOfMonth)'](https://docs.oracle.com/javase /8/docs/api/java/time/LocalDate.html#of-int-int-int-) – MadProgrammer

回答

2

如果可能的話,你應該使用LocalDate.of(year, month, dayOfMonth)

LocalDate date = LocalDate.of(startYear, startMonth, startDay); 

一氣,你可以創建一個String表示和解析它

String dateValue = startYear + "/" + startMonth + "/" + startDay; 
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); 
Date data = sdf.parse(dateValue); 

但是考慮LocalDate簡單,我會去說...另外,如果你使用的是Java 8或更高版本,那麼你應該不會真的在使用java.util.Date,即使你沒有,也可以考慮使用JodaTime而不是java.util.Date

+0

完全同意。儘管如此,他們說你應該更喜歡JodaTime的[Java SE 8日期 - 時間類的三倍數據返回到Java SE 6和7](http://www.threeten.org/threetenbp/)。如果您以後更改爲Java 8,我希望這會給您帶來很大的兼容性。 –

相關問題