日期:2014-05-20  浏览次数:20868 次

关于String 日期相减问题。请大家帮帮忙 谢谢
例如:

String data1 = "20090909";
String data2 = "20100101";

data2 - data1 求出相差的月份!

------解决方案--------------------
送你个例子吧
Java code

/**
 * 求月数差
 * 
 * @param strDate1    日期1    yyyy/MM/dd
 * @param strDate2    日期2    yyyy/MM/dd
 * @return 月数差
 * @throws ParseException 日期格式错误
 */
public static int differenceMonth(String strDate1, String strDate2) 
    throws ParseException {
    Date date1 = DateFormat.getDateInstance().parse(strDate1);
    Date date2 = DateFormat.getDateInstance().parse(strDate2);
    return differenceMonth(date1,date2);
}

public static int differenceMonth(Date date1, Date date2) {
    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(date1);
    cal1.set(Calendar.DATE, 1);
    Calendar cal2 = Calendar.getInstance(); 
    cal2.setTime(date2);
    cal2.set(Calendar.DATE, 1);
    int count = 0;
    if (cal1.before(cal2)) {
        while (cal1.before(cal2)) {
            cal1.add(Calendar.MONTH, 1);
            count--;
        }
    } else {
        count--;
        while (!cal1.before(cal2)) {
            cal1.add(Calendar.MONTH, -1);
            count++;
        }
    }
    return count;
}

------解决方案--------------------
这不是很难吧,直接写就能写出来
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
Date firstDate = firstDate = df.parse(data1);
Date secondDate = secondDate = df.parse(data2);
return secondDate.getMonth()-firstDate.getMonth()+12*(secondDate.getYear()-firstDate.getYear());

我没处理异常啊。
------解决方案--------------------
使用 joda-time

Java code
import org.joda.time.*;
import org.joda.time.format.*;

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");

DateTime d1 = formatter.parseDateTime("20090909");
DateTime d2 = formatter.parseDateTime("20100101");

Period p = new Period(d1,d2,PeriodType.months());

PeriodFormat.getDefault().print(p); // 3 months