package com.ruoyi.test;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 生成1年内的间隔为1个月的开始结束时间
 */
public class TestDateYear {

    public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    public static void main(String[] args) throws Exception {
        Date start = format.parse("2023-01-01");
        Date end = format.parse("2023-12-31");
        splitByMonth(start, end);
    }

    /**
     * 生成任务的开始时间和结束时间
     *
     * @param start 开始时间
     * @param end   结束时间
     */
    public static void splitByMonth(Date start, Date end) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        int index = 1;
        while (calendar.getTime().before(end)) {
            Date startTime = calendar.getTime();
            Date nextMonth = getNextMonth(calendar);
            //结束时间往前偏移1天
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(nextMonth);
            Date endTime = getNextDateOfMonth(endCalendar);
            System.out.println(index++ + "\t" + format.format(startTime) + "\t" + format.format(endTime));
            calendar.setTime(nextMonth);
        }
    }

    /**
     * 日期偏移 单位：月
     *
     * @param calendar
     * @return
     */
    public static Date getNextMonth(Calendar calendar) {
        Calendar nextMonthCalendar = Calendar.getInstance();
        nextMonthCalendar.setTime(calendar.getTime());
        nextMonthCalendar.add(Calendar.MONTH, 1);

        return nextMonthCalendar.getTime();
    }

    /**
     * 日期偏移 单位：天
     *
     * @param calendar
     * @return
     */
    public static Date getNextDateOfMonth(Calendar calendar) {
        Calendar nextMonthCalendar = Calendar.getInstance();
        nextMonthCalendar.setTime(calendar.getTime());
        nextMonthCalendar.add(Calendar.DAY_OF_MONTH, -1);

        return nextMonthCalendar.getTime();
    }

}
