Java 代码获取指定年月所有日期
以下是 Java 代码实现,根据给定的年月字符串,获取该月份的所有日期:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String yearMonth = '2022-08'; // 要获取的年月字符串
List<LocalDate> daysOfMonth = getDaysOfMonth(yearMonth);
for (LocalDate day : daysOfMonth) {
System.out.println(day.toString()); // 输出每一天的日期字符串
}
}
private static List<LocalDate> getDaysOfMonth(String yearMonth) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern('yyyy-MM');
LocalDate firstDayOfMonth = LocalDate.parse(yearMonth + '-01', formatter); // 获取当前月份的第一天
LocalDate lastDayOfMonth = firstDayOfMonth.withDayOfMonth(firstDayOfMonth.lengthOfMonth()); // 获取当前月份的最后一天
List<LocalDate> daysOfMonth = new ArrayList<>();
for (LocalDate date = firstDayOfMonth; date.isBefore(lastDayOfMonth.plusDays(1)); date = date.plusDays(1)) {
daysOfMonth.add(date); // 将每一天添加到列表中
}
return daysOfMonth;
}
}
解释:
yearMonth是要获取的年月字符串。getDaysOfMonth方法接收一个年月字符串,返回该月份的每一天的LocalDate对象列表。DateTimeFormatter类用于将字符串解析为日期对象。LocalDate类代表日期,withDayOfMonth方法可以将日期设置为当前月份的最后一天。- 通过循环遍历每一天,将其添加到列表中。
- 最后输出每一天的日期字符串。
原文地址: https://www.cveoy.top/t/topic/ngKv 著作权归作者所有。请勿转载和采集!