java.time.DateTimeException:无效的日期';2月29日和27日;as';2017年&x27年;不是闰年
我试图用Java获取开始和结束日期,我在java.time.DateTimeException:无效的日期';2月29日和27日;as';2017年&x27年;不是闰年,java,date,jcombobox,localdate,Java,Date,Jcombobox,Localdate,我试图用Java获取开始和结束日期,我在JCombobox中列出了从1月到12月的月份列表,并在JCombobox中列出了年份以显示年份 首先,我已将字符串转换为月份编号,并使用此代码: if(month_sands.getSelectedIndex() != -1){ int monthnumber = month_sands.getSelectedIndex() + 1; if(monthnumber>=9) {
JCombobox
中列出了从1月到12月的月份列表,并在JCombobox
中列出了年份以显示年份
首先,我已将字符串
转换为月份编号,并使用此代码:
if(month_sands.getSelectedIndex() != -1){
int monthnumber = month_sands.getSelectedIndex() + 1;
if(monthnumber>=9)
{
month=String.valueOf(monthnumber);
}else
{
month="0"+String.valueOf(monthnumber);
}
}
然后,我创建了一个字符串dateString
,使用LocalDate
获取所选月份的第一个和最后一个日期,一切正常,但当我选择2017年2月和2017年时,它会给我异常java.time.DateTimeException:无效日期“2月29日”,因为“2017”不是闰年
获取第一个和最后一个日期的代码是
try {
String dateString = year_sands.getSelectedItem().toString()+"-"+month+"-"+"01";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.US);
LocalDate date = LocalDate.parse(dateString, dateFormat);
LocalDate startDate=date.withDayOfMonth(1);
LocalDate endDate = date.withDayOfMonth(date.getMonth().maxLength());
start_date=startDate.toString();
end_date=endDate.toString();
System.out.println(start_date);
System.out.println(end_date);
} catch (Exception e) {
e.printStackTrace();
}
我不知道我做错了什么,请有人帮帮我这是因为您在这行中使用了
maxLength()
:
LocalDate endDate = date.withDayOfMonth(date.getMonth().maxLength());
方法maxLength()
返回本月的最大长度(以天为单位),如。事实上,2月份的天数最多为29天(只是2017年没有,但这是一般的2月份,而不是任何特定年份!)
这应该是可行的,因为它考虑了特定年份的月份长度:
LocalDate endDate = date.withDayOfMonth(date.lengthOfMonth());
该方法不适用于确定2月的上下文相关长度(28天或29天)。这种方法的结果总是29
<>你应该考虑这个方法。< /P>
试试上面的代码。
希望这能对你有所帮助。我知道,但你能解释一下例外情况是如何产生的吗,请包含异常的完整堆栈跟踪——和/或在代码中添加注释,解释异常发生在哪一行。好的,我得到了帮助Meno Hochschild+1的答案。谢谢。请回答:请回答:
String dateString = year_sands.getSelectedItem().toString()+"-"+month+"-"+"01";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.US);
LocalDate date = LocalDate.parse(dateString, dateFormat);
LocalDate startDate = date.withDayOfMonth(1);
LocalDate endDate = null;
if (Integer.parseInt(month) == 02) {
if (isLeapYear(Integer.parseInt(year_sands.getSelectedItem().toString()))) {
endDate = LocalDate.parse(year_sands.getSelectedItem().toString() + "-02" + "-29", dateFormat);
}
else
{
endDate = LocalDate.parse(year_sands.getSelectedItem().toString() + "-02" + "-28", dateFormat);
}
} else {
endDate= date.withDayOfMonth(date.getMonth().maxLength());
}
public static boolean isLeapYear(int year) {
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
return true;
} else {
return false;
}
}