已知兩個日期,打印出兩個日期之間的全部月份

已知兩個日期,打印出兩個日期之間的全部月份

添加工具類 工具類代碼詳情內容:markdown

public static void main(String[] args) {

String s = "201801 ~ 202001";

String[] split = s.split(" ~ ");

int afterMonth;

int beforeMonth;

int beforeYear;

int afterYear;

int currentYear;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

String before = split[0] + "01";
String after = split[1] + "01";

LocalDate beforeLocalDate = LocalDate.parse(before, formatter);

LocalDate afterLocalDate = LocalDate.parse(after, formatter);

beforeMonth = beforeLocalDate.getMonthValue();

afterMonth = afterLocalDate.getMonthValue();

beforeYear = beforeLocalDate.getYear();

afterYear = afterLocalDate.getYear();

int diff = (afterMonth - beforeMonth) + (afterYear - beforeYear) * 12;

currentYear = beforeLocalDate.getYear();
List<String> list = new ArrayList<>();

String date;
if (diff > 0){
    for (int i = 0; i < diff - 1; i++) {
        beforeMonth = beforeMonth + 1;

        if (beforeMonth < 9) {
            date = currentYear + "-" + "0" + beforeMonth;
        } else {
            date = currentYear + "-" + beforeMonth;
        }

        if (beforeMonth % 12 == 0) {
            currentYear++;
            beforeMonth = 0;
        }

        list.add(date);
    }
}

System.err.println(list);

}
複製代碼

在這裏插入圖片描述

相關文章
相關標籤/搜索