日期:2014-05-19  浏览次数:20787 次

给两个时间:起始日期和终止日期,求一函数,把它的月数列出来,要可以跨年跨月的。
给两个时间:起始日期和终止日期,比如2008-12-25 2009-01-10,求一函数,把它的月数列出来,要可以跨年。
得出下面结果:
2008-10-25至2008-10-31  
2008-11-01至2008-11-30  
2008-12-01至2008-12-31  
2009-01-01至2009-01-31  
2009-02-01至2009-02-28
2009-03-01至2009-03-10


------解决方案--------------------
Java code

    private static void printYearMonth(String start, String end) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date s = sdf.parse(start);
        Date e = sdf.parse(end);
        Calendar cals = Calendar.getInstance();
        cals.setTime(s);
        Calendar cale = Calendar.getInstance();
        cale.setTime(e);
        StringBuffer sb = new StringBuffer();
        while (cals.before(cale)) {
            sb.append(sdf.format(cals.getTime()));
            sb.append("至");
            cals.set(Calendar.DATE, 1);
            cals.add(Calendar.MONTH, 1);
            if (cals.after(cale)) {
                cals = cale;
                sb.append(sdf.format(cals.getTime()) + "\n");
                break;
            }
            cals.add(Calendar.DATE, -1);
            sb.append(sdf.format(cals.getTime()) + "\n");
            cals.add(Calendar.DATE, 1);

        }
        System.out.print(sb.toString());
    }