SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");改为:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");/*
m Minute in hour Number 30
M Month in year Month July; Jul; 07
*/
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");/*
m Minute in hour Number 30
M Month in year Month July; Jul; 07
*/
俺给你重构实现了另一种方法,你看看:
public class MonthPeriodExtend {
private MonthPeriodExtend() {} private static final long MS_PER_DAY = (long)(24*3600*1000); public static Date RelativeDate(Date currentDate, int offset) {
if (currentDate==null) throw new NullPointerException();
if (currentDate.getTime()+offset*MS_PER_DAY<0) throw new IllegalArgumentException(); return new Date(currentDate.getTime()+ offset*MS_PER_DAY);
}
}
单元测试的代码也放到下面:
public class TestMonthPeriodExtend extends TestCase {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); public TestMonthPeriodExtend(String name) {super(name);} public void testRelativeDate() throws Exception {
Date d1 = DATE_FORMAT.parse("2003-11-24"); assertEquals(DATE_FORMAT.parse("2003-11-27"), MonthPeriodExtend.RelativeDate(d1, 3));
assertEquals(DATE_FORMAT.parse("2003-11-21"), MonthPeriodExtend.RelativeDate(d1, -3)); validateNullPointerException();
validateIllegalArgumentException();
} // private :
private void validateNullPointerException() {
boolean exception = false;
try {MonthPeriodExtend.RelativeDate(null, 1);}
catch(NullPointerException ex) {exception=true;}
assertTrue(exception);
} private void validateIllegalArgumentException() {
boolean exception = false;
try {
MonthPeriodExtend.RelativeDate(new Date(0), -1);
} catch(IllegalArgumentException ex) {
exception = true;
}
assertTrue(exception); exception = false;
try {
MonthPeriodExtend.RelativeDate(new Date(Long.MAX_VALUE), 1);
} catch(IllegalArgumentException ex) {
exception = true;
}
assertTrue(exception);
}
}
BTW,你使用SimpleDateFormat的PATTERN错了,应该是"yyyy-MM-dd",修改后你再试试。
-----------------------------------------------------^^ 换成下面的,小写的代表分钟
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
public class testDate
{
public static void main(String[] args)
{
Date DateNow=new Date(2003,9,14);
int n=2;
String str_date = null;
Calendar cal = Calendar.getInstance();
cal.setTime(DateNow);
cal.add(Calendar.DATE,n);
str_date = cal.get(cal.YEAR)+"-"+(cal.get(cal.MONTH)+1)+"-"+cal.get(cal.DATE);
System.out.println("str_date: "+str_date);
}
}
俺沒發現任何問題,不信你改一下日期。