好的,问题来了,我正在尝试制作一种方法,它可以帮助我将从日期 A 到日期 B 的所有日期放入列表中,并将日期类型放在它的前面,例如: 日期 A- 2013 年 1 月 1 日 日期 B- 2013 年 1 月 3 日
结果应该是这样的
01-01-2013 星期二
02-01-2013 星期三
03-01-2013 星期四
这应该在 map /列表中。
我厌倦了以下方法,首先至少在列表中包含日期,但出现 Java 堆空间不足错误。
public static List<ShiftDate> createShiftDate() {
String startDate = "2013-01-01";
String lastDate = "2013-01-28";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
List<ShiftDate> shiftDateList = new ArrayList<ShiftDate>();
ShiftDate shiftDate = new ShiftDate();
try {
Date startDate1 = formatter.parse(startDate);
Date endDate1 = formatter.parse(lastDate);
Calendar c = Calendar.getInstance();
Date newDate = startDate1;
while (newDate.compareTo(endDate1) < 0) {
c.setTime(newDate);
c.add(Calendar.DATE, 1);
shiftDate.setDateString(c.getTime().toString());
shiftDateList.add(shiftDate);
}
} catch (ParseException e) {
e.printStackTrace();
}
for (ShiftDate shiftDate1 : shiftDateList) {
System.out.println(shiftDate1);
}
return shiftDateList;
}
最佳答案
您没有更新循环条件变量 (
newDate
)。它应该看起来像这样:while (newDate.compareTo(endDate1) < 0) { c.setTime(newDate); c.add(Calendar.DATE, 1); newDate = c.getTime(); shiftDate.setDateString(c.getTime().toString()); shiftDateList.add(shiftDate); }
其他问题:您将格式化程序设置为 dd-MM-yyyy 模式,但实际日期采用 yyyy-MM-dd 模式。
此外,您每次都需要创建一个新的 ShiftDate 实例,否则每次都需要。否则您最终会得到包含相同(最后更新)日期值的整个列表。
while (newDate.compareTo(endDate1) < 0) { c.setTime(newDate); c.add(Calendar.DATE, 1); newDate = c.getTime(); shiftDate = new ShiftDate(); shiftDate.setDateString(c.getTime().toString()); shiftDateList.add(shiftDate); }
关于java - Java中的日期列表递增方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21848648/