2017-05-04 124 views
1

我嘗試獲取Java中的開始日期和結束日期,我有JCombobox年和1月份的月份列表JCombobox到Dispay年。java.time.DateTimeException:無效日期'2月29日'爲'2017'不是閏年Java

首先我必須轉換String個月到一個月數量和使用此代碼:

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所選月份的最後日期,每一件事情是工作正常,但是當我選擇了2月月至2017年這一年給我異常java.time.DateTimeException: Invalid date 'February 29' as '2017' is not a leap year

獲取的第一和最後一個日期代碼是

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

我不知道我做錯了,請有人幫我

+0

我知道,但如何引發異常,您可以解釋 –

+0

順便說一下,在將來,請包括異常的完整堆棧跟蹤 - 和/或添加一個註釋到您的代碼解釋哪一行異常發生了。 – yshavit

+0

好吧,我得到了我的答案 –

回答

9

這是因爲你在這一行使用maxLength()

LocalDate endDate = date.withDayOfMonth(date.getMonth().maxLength()); 

maxLength()返回天這個月的最大長度的方法,正如API documentation所說。二月份的確最多有29天(不是在2017年,但這大概是二月份的總體月份,而不是在任何特定的一年!)。

這應該工作,因爲它需要一個月的長度在特定年份考慮:

LocalDate endDate = date.withDayOfMonth(date.lengthOfMonth()); 
+0

幫助Jesper +1謝謝很多人 –

3

方法maxLength()不適合確定日的上下文相關的長度(無論是28或29天)。該方法始終產生29.

您應該考慮方法lengthOfMonth()

+0

幫助Meno Hochschild +1非常感謝 –

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

試試上面的代碼。 希望這會幫助你。

相關問題