我已将年,月,日放在单独的JComboBoxes
上,月份JComboBox有自己的渲染器
来显示月份名称而不是整数
值月。月份从 0 开始(0-January....11-December)
所以,我的问题是如何将年、月、日放在一起并将其分配给 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。
我担心当我提取月份来检查冲突时,这可能会被解读为一月而不是二月。
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
数据库中。
有什么想法或建议吗?
谢谢。
最佳答案
如果可能的话,您应该使用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.lang. util.Date
在你可以的地方,即使你不能,我还是会考虑使用 JodaTime 而不是 java.util.Date
关于java - 将 JComboBox 年、月、日整数值连接或格式化为日期类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42667856/