将月份添加到特定的java.sql.Date

将月份添加到特定的java.sql.Date,java,Java,如何向数据库中存储的日期添加特定的月数 private Date getStartDate(){ return new Date(Calendar.getInstance().getTimeInMillis()); } private Date getEndDate(){ startDate = userSubscription.getSubscriptionStartDate(); Date endDate; Calendar calendar = C

如何向数据库中存储的日期添加特定的月数

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;
}
例如,您可以通过以下方式添加1个月:

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

只需将变量(我假设月数)转换为int

我建议使用不同的时间库,例如joda的。您可以在joda library中执行类似操作:

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

首先是一个旁注-此代码还可以在“getStartDate”方法中返回一个新日期:

回答你的问题:

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

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

以避免使用当月的最后一天或一年中的最后一个月。重写代码的一种可能方法:

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();
}

你所说的“无长型参数”是什么意思?如果你在一年结束前总结一下,这将不会很好地发挥作用。这正是
add
的目的。我同意,很抱歉弄错了。
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();
}