Fer*_*iva 2 java date jodatime
我正在尝试用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;
}
Run Code Online (Sandbox Code Playgroud)
我怎么能解决这个问题?
Roh*_*ain 16
问题是,您将一个月值传递给DateTime构造函数,该构造函数不在范围内.如果构造函数溢出到下一个更高的字段,则它不会滚动值.如果任何字段超出范围,它会抛出异常,这里的月份14肯定超出范围[1, 12].
您可以简单地使用类中的plusMonths()方法DateTime来添加月份,而不是使用当前的方法:
DateTime now = DateTime.now();
DateTime sixMonthsLater = now.plusMonths(6);
Run Code Online (Sandbox Code Playgroud)
如果溢出,这将自动滚动月份值.
在data.getMonthOfYear()将返回当前月份是August手段8,但你加6,这意味着mes成为14这是不是一个有效MonthOfYear从而导致对IllegalFieldValueException: Value 14.
您可以使用DateTime该类的plus方法
样品:
DateTime dt = new DateTime(); //will initialized to the current time
dt = dt.plusMonths(6); //add six month prior to the current date
Run Code Online (Sandbox Code Playgroud)
文件:
plusMonths(int months)
Returns a copy of this datetime plus the specified number of months.
Run Code Online (Sandbox Code Playgroud)