2015-06-15 64 views
-3

我想根據日期產生一個列表。我不斷收到一個Parse異常。我以爲我的日期完全一樣。也許我錯過了什麼。我已經玩了幾個小時沒有成功。任何幫助,將不勝感激。無法解析的日期。解析異常比較兩個日期

public static List<String> getMonthlyDates(Date startdate, Date enddate) { 
    List<String> dates = new ArrayList<String>(); 
    Calendar calendar = new GregorianCalendar(); 


    calendar.setTime(startdate); 

    while (calendar.getTime().before(enddate)) { 
     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
     String result = df.format(calendar.getTime()); 
     dates.add(result); 
     calendar.add(Calendar.MONTH, 1); 
    } 
    return dates; 
} 

Calendar Mcalendar = Calendar.getInstance(); 
String dd = editbillduedate.getText().toString(); 
    //Which shows correctly in the format of 2015-Jun-15 
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
    //it makes no difference if format is yyyy-mm-dd 
Date date; 
     try { 
//THIS LINE BELOW IS WHERE I AM GETTING THE ERROR 
      date = format.parse(dd); 
      Mcalendar.add(Calendar.DAY_OF_YEAR, 365); 
      final Date newDate2 = Mcalendar.getTime(); 

      List<String> dateList = getMonthlyDates(date, newDate2); 

      for (final String d1 : dateList) { 
      //Does something irrelevant 

      } 
      } catch (ParseException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      } 
+0

你成爲這一行什麼樣的字符串'字符串dd = editbillduedate.getText()。toString();'?你可以請調試並粘貼「dd」變量的值嗎? –

+0

java.text.ParseException:Unparseable date:「2015-Jun-15」(at offset 5) – SmulianJulian

+1

我想我明白了,請看看下面的答案:) –

回答

1

如果你想在喜歡2015-Jun-15相同的格式解析日期,你應該改變你的SimpleDateFormat有像這樣的月份元素三個大字:yyyy-MMM-dd。因此,改變這種:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 

到:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd"); 

這:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 

到:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MMM-dd"); 
+0

好的,好的。也許我確實應該得到一些讚譽。現在我懂了。 MM是數字月,正確。 MMM是月份的前三個字母。 EditText採用MMM格式,我要求MM。明白...哇。我不相信我花了2個小時應該需要5秒鐘才能弄清楚。謝謝。 – SmulianJulian

+0

:D是的,有時候會發生這種情況:)不客氣:)並且儘量不關心downvotes,因爲這些仇敵無處不在.... –