欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

获取指定时间前12个月(包含当前月)

程序员文章站 2024-01-18 08:19:34
/** * 获取指定时间最近12月的年月(含当月) * */ public static String[] getLatest12Month(String date){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); Date parse = null; try { parse = sdf.parse(date);} catch (ParseExc......
    /**
    * 获取指定时间最近12月的年月(含当月)
    * 
    */
    public static String[] getLatest12Month(String date){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");  
    	Date parse = null;
        try {
	    parse = sdf.parse(date);
	} catch (ParseException e) {
            e.printStackTrace();
	}
    	String[] months = new String[12];
        Calendar cal = Calendar.getInstance();
        cal.setTime(parse);
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
        // 加一行代码,否则3月重复
        cal.set(Calendar.DATE,1);
        for (int i = 0; i < 12; i++) {
            months[11 - i] = cal.get(Calendar.YEAR) + "-" +           fillZero(cal.get(Calendar.MONTH) + 1);
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);
        }
    	return months;
    }
	
    /**
    * 格式化月份
    */
    public static String fillZero(int i) {
	String month = "";
	if (i < 10) {
	    month = "0" + i;
	} else {
	    month = String.valueOf(i);
	}
	return month;
    }

 

本文地址:https://blog.csdn.net/gunicoin/article/details/109615143

相关标签: 时间