我正在尝试根据日期生成一个列表。我一直得到一个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 :(得分: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");