2014-09-26 48 views
0

如何将特定的月数添加到存储在数据库中的日期。将个月添加到特定的java.sql.Date日期

private Date getStartDate(){ 
     return new Date(Calendar.getInstance().getTimeInMillis()); 
} 

private Date getEndDate(){ 
    startDate = userSubscription.getSubscriptionStartDate(); 
    Date endDate; 
    Calendar calendar = Calendar.getInstance(); 
    //Now I am having trouble cause in add() method of calendar there is no long type parameter 
    return endDate; 
} 
+0

你是什么意思“无长型参数”? – 2014-09-26 12:58:57

回答

1

例如,你可以通过加1月份:

calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)+1); 

只要投你的变量(我假设月数)为int。

我推荐使用不同的时间库,例如joda's。你可以做这样的事情在乔达库:

Date date = new Date(); 
DateTime dateTime = new DateTime(date); 
dateTime.plusMonths(1); 
return dateTime.toDate(); 
+1

如果你在一年的周末结束,那么这种方法不会奏效。这正是“添加”的意思。 – 2014-09-26 12:59:25

+0

我同意,因为错误。 – Tomek 2014-09-26 13:11:11

0

首先一个侧面说明 - 此代码也将努力在“getStartDate”方法返回一个新日期:

return new Date(); 

要回答你的问题:

calendar.add(Calendar.MONTH, x); 
endDate = calendar.getTime(); 

其中“x”表示要添加的月数。

0

为了避免月份的最后一天或一年中的上个月,您可以使用GregorianCalendar#roll(..)。一种可能的重写代码的方法:

private Date getEndDate(){ 
    //... 
    Calendar calendar = GregorianCalendar.getInstance(); 
    //Now I am having trouble cause in add() method of calendar there is no long type parameter 
    c.setTime(userSubscription.getSubscriptionStartDate()); 
    c.roll(Calendar.MONTH, 1); 
    return c.getTime(); 
}