java中获取当前日期的前六个月(自己可配置查几个月)

package com.atguigu.yygh.cmn.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

class ceshi {
    public static void main(String[] args) throws ParseException {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -5);//在这块修改查询的是前几个月
        String before_six = c.get(Calendar.YEAR) + "/" + c.get(Calendar.MONTH);//六个月前
        ArrayList result = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");// 格式化为年月
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        min.setTime(sdf.parse(before_six));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
        max.setTime(sdf.parse(sdf.format(new Date())));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }
        List strings = result.subList(0, result.size()-1 );
        System.out.println(strings);
       /* for (int i = 0; i < result.size(); i++) {
            String[] result1 = result.get(i).toString().split("/");
            System.out.println(result1[1] + "第" + result.get(i));
        }*/
    }
}

直接复制包运行

你可能感兴趣的:(java,python,开发语言)