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

如何获得上个月?
如何通过calendar类的roll或者add方法得到上个月

2007-1-1   上个月是   2006-12
2007-2-28   上个月是   2007-1

------解决方案--------------------
import java.text.*;
import java.util.*;

public class Test58 {

private static SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd ");

private static SimpleDateFormat sdf2 = new SimpleDateFormat( "yyyy-MM ");

public static void main(String[] args) throws Exception {
System.out.println(getLastMonth( "2007-1-1 "));
System.out.println(getLastMonth( "2007-2-28 "));

}

public static String getLastMonth(String thisMonth) throws Exception {
Date d = sdf.parse(thisMonth);
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.MONTH, -1);
d = calendar.getTime();
return sdf2.format(d);
}

}