所有现有的答案都很棒。这个答案提供了一些额外的信息,这些信息也可以解决您的问题或至少引导您朝着正确的方向前进。
使用现代 API:
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2020, 12, 5);// 5th Dec 2020
LocalDate endDate = LocalDate.of(2020, 12, 15);// 15th Dec 2020
for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
System.out.println(date);
}
}
}
输出:
2020-12-05
2020-12-06
2020-12-07
2020-12-08
2020-12-09
2020-12-10
如果您将日期作为字符串对象:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d/M/uuuu");
LocalDate startDate = LocalDate.parse("5/12/2020", dtf);// 5th Dec 2020
LocalDate endDate = LocalDate.parse("10/12/2020", dtf);// 10th Dec 2020
for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
System.out.println(date);
}
}
}
输出:
2020-12-05
2020-12-06
2020-12-07
2020-12-08
2020-12-09
2020-12-10
使用旧版 API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(2020, 11, 5);// 5th Dec 2020
Date startDate = calendar.getTime();
calendar.set(2020, 11, 10);// 10th Dec 2020
Date endDate = calendar.getTime();
SimpleDateFormat sdfForOutput = new SimpleDateFormat("yyyy-MM-dd");
Date date = startDate;
for (calendar.setTime(startDate); !date.after(endDate); calendar.add(Calendar.DAY_OF_YEAR,
1), date = calendar.getTime()) {
System.out.println(sdfForOutput.format(date));
}
}
}
输出:
2020-12-05
2020-12-06
2020-12-07
2020-12-08
2020-12-09
2020-12-10
如果您将日期作为字符串对象:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
class Main {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdfForParsing = new SimpleDateFormat("d/M/yyyy");
Date startDate = sdfForParsing.parse("5/12/2020");// 5th Dec 2020
Date endDate = sdfForParsing.parse("10/12/2020");// 10th Dec 2020
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdfForOutput = new SimpleDateFormat("yyyy-MM-dd");
Date date = startDate;
for (calendar.setTime(startDate); !date.after(endDate); calendar.add(Calendar.DAY_OF_YEAR,
1), date = calendar.getTime()) {
System.out.println(sdfForOutput.format(date));
}
}
}
输出:
2020-12-05
2020-12-06
2020-12-07
2020-12-08
2020-12-09
2020-12-10
请注意,java.util 的日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到modern date-time API。通过 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
注意:出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它向后移植了大部分 java.time 功能到 Java 6 和 7。
如果您正在为一个 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。