java 得到 时间段内 有多少个月 或者 多少天 代码

来源:互联网 发布:传奇霸业道士宝石数据 编辑:程序博客网 时间:2024/04/28 02:48

 public static String getMonthList(String beginDateStr, String endDateStr) {

    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM");
    //返回的月份列表
    String sRet = "";
   
    //定义一些变量
    Date beginDate = null;
    Date endDate = null;
   
    GregorianCalendar beginGC = null;
    GregorianCalendar endGC = null;
   
    try {
        //将字符串parse成日期
        beginDate = f.parse(beginDateStr);
        endDate = f.parse(endDateStr);
       
        //设置日历
        beginGC = new GregorianCalendar();
        beginGC.setTime(beginDate);
       
        endGC = new GregorianCalendar();
        endGC.setTime(endDate);
       
        //直到两个时间相同
        while(beginGC.getTime().compareTo(endGC.getTime())<=0){
            //累加字符串,用单引号分隔
            if (sRet.equals("")) {
                sRet += beginGC.get(Calendar.YEAR) + "-" + (beginGC.get(Calendar.MONTH)+1);
            }
            else {
                sRet += "," + beginGC.get(Calendar.YEAR) + "-" + (beginGC.get(Calendar.MONTH)+1);   
            }
           
            //以月为单位,增加时间
            beginGC.add(Calendar.MONTH,1);
        }
        return sRet;
    }
    catch(Exception e) {
        e.printStackTrace();
        return null;
    }
}

0 0
原创粉丝点击