我正在尝试用JodaTime添加一个月。我有一个付款计划与一些月,例如:一个月,两个月,三个月和六个月。
当我在DateTime添加六个月的时候不工作并返回一个异常。
我在试这个。
/** cria data vencimento matricula */
public void getDataVencimento(Integer dia, Integer planoPagamento){
//monta data para JodaTime
DateTime data = new DateTime();
Integer ano = data.getYear();
Integer mes = data.getMonthOfYear() + 6; //here 6 month
//monta a data usando JodaTime
DateTime dt = new DateTime(ano, mes, dia, 0, 0);
//convert o datetime para date
Date dtVencimento = dt.toDate();
System.out.println(df.format(dtVencimento));
//retorna a proxima data vencimento
// return dtVencimento;
}
/** exception */
Exception in thread "AWT-EventQueue-0" org.joda.time.IllegalFieldValueException: Value 14 for monthOfYear must be in the range [1,12]
/** I did this and now works */
/** cria data vencimento */
public Date getDataVencimento(Integer dia, Integer planoPagamento){
//monta data para JodaTime
DateTime data = DateTime.now();//pega data de hoje
DateTime d = data.plusMonths(planoPagamento);//adiciona plano de pagamento
//cria data de vencimento
DateTime vencimento = new DateTime(d.getYear(), d.getMonthOfYear(), dia, 0, 0);
//convert o datetime para date
Date dtVencimento = vencimento.toDate();
//retorna a proxima data vencimento
return dtVencimento;
}我该如何解决这个问题?
发布于 2014-08-14 12:42:11
问题是,您正在向DateTime构造函数传递一个Month值,该值不在范围内。如果构造函数溢出到下一个更高的字段,则它不会滚动值。如果任何字段超出范围,它就会抛出一个异常,这里的14是肯定超出范围的[1, 12]。
您可以简单地使用DateTime类中的plusMonths()方法来添加月份,而不是使用当前方法:
DateTime now = DateTime.now();
DateTime sixMonthsLater = now.plusMonths(6);这将自动滚动月份值,如果它溢出。
发布于 2014-08-14 12:34:41
data.getMonthOfYear()将返回当前月份,即August,意思是8,但是您添加了6,这意味着mes变成了14,这不是一个有效的<代码>D9,因此结果为<代码>D10。
您可以使用DateTime类的加号方法
示例:
DateTime dt = new DateTime(); //will initialized to the current time
dt = dt.plusMonths(6); //add six month prior to the current dateDocumentation
plusMonths(int months)
Returns a copy of this datetime plus the specified number of months.发布于 2014-08-14 12:34:49
最简单的方法如下所示,使用plus方法向DateTime对象添加6个月的周期:
import org.joda.time.DateTime;
import org.joda.time.Months;
// ...
DateTime now = new DateTime();
DateTime sixMonthsLater = now.plus(Months.SIX);https://stackoverflow.com/questions/25300140
复制相似问题