根据两个时间段,取这两个时间段内有多少个月份

根据两个时间段,取这两个时间段内有多少个月份




/*
 * 创建日期 2004-11-29
 *
 *
 */
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


/**
 * @author wubai
 *
 *根据两个时间段,取这两个时间段内有多少个月份
 *
 */
public class Test {
    public String getMonthList(String beginDateStr, String endDateStr) {
        //指定要解析的时间格式
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        //返回的月份列表
        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;
        }
    }
   
    //测试用
    public static void main(String[] args) {
        Test test = new Test();
        String tmp;
        tmp = test.getMonthList("2004-03-09", "2004-08-10");
        System.out.println("month list:" + tmp);
       
        //返回结果如下:
        //month list:2004-3,2004-4,2004-5,2004-6,2004-7,2004-8
        //也就是说月份前没有加0补全,为了程序的简洁,所以没有加,可以自己补全

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值