在Java中,可以使用java.time.LocalDate
类来处理日期。下面是一个示例代码,演示如何获取两个日期之间的所有日期:
import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { LocalDate startDate = LocalDate.of(2022, 1, 1); LocalDate endDate = LocalDate.of(2022, 1, 10); ListallDates = new ArrayList<>(); LocalDate currentDate = startDate; while (currentDate.isBefore(endDate) || currentDate.isEqual(endDate)) { allDates.add(currentDate); currentDate = currentDate.plusDays(1); } for (LocalDate date : allDates) { System.out.println(date); } } }
在上面的示例中,startDate
和endDate
分别表示要获取的日期范围的起始日期和结束日期。allDates
是一个列表,用于存储所有的日期。currentDate
是一个当前日期变量,初始值为起始日期。
使用while
循环,我们在currentDate
小于等于结束日期时,将当前日期添加到allDates
列表中,并将currentDate
增加一天。最后,我们遍历allDates
列表,并打印每个日期。
输出将是从2022年1月1日到2022年1月10日的所有日期。