Java将日期范围按月份进行拆分

x33g5p2x  于2021-03-08 发布在 Java  
字(1.4k)|赞(0)|评价(0)|浏览(523)

使用java将一个日期范围[startDate,endDate]按月进行拆分。
代码如下:

public class DateRangeUtils {

    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    private final static SimpleDateFormat monthSdf = new SimpleDateFormat("yyyyMM");


    private static List<Triplet<String,String,String>> getMonths(String begins, String ends) {
        List<Triplet<String,String,String>> ret = new ArrayList<>();
        try {
            Date begin = sdf.parse(begins);
            Date end = sdf.parse(ends);
            Calendar calBegin = Calendar.getInstance();
            calBegin.setTime(begin);
            Calendar calEnd = Calendar.getInstance();
            calEnd.setTime(end);
            while (true) {
                if (calBegin.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)&& calBegin.get(Calendar.MONTH) == calEnd.get(Calendar.MONTH)) {
                    ret.add(Triplet.with(monthSdf.format(calBegin.getTime()),sdf.format(calBegin.getTime()),sdf.format(calEnd.getTime())));
                    break;
                }
                ret.add(Triplet.with(monthSdf.format(calBegin.getTime()),sdf.format(calBegin.getTime()),getMonthEnd(calBegin.getTime())));
                calBegin.add(Calendar.MONTH, 1);
                calBegin.set(Calendar.DAY_OF_MONTH, 1);
            }
        } catch (ParseException e) {
            System.out.println("日期输入格式不对");
        }
        return ret;
    }
	
	
	public static void main(String[] args) {
        String startDate = "20210102";
        String endDate = "20210302";
       System.out.println(getMonths(startDate,endDate));
    }
}
	

输入为:

[[202101, 20210102, 20210131], [202102, 20210201, 20210228], [202103, 20210301, 20210302]]

相关文章

热门文章

更多