首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否使用JodaTime添加月份?

是否使用JodaTime添加月份?
EN

Stack Overflow用户
提问于 2014-08-14 12:31:45
回答 3查看 10.3K关注 0票数 3

我正在尝试用JodaTime添加一个月。我有一个付款计划与一些月,例如:一个月,两个月,三个月和六个月。

当我在DateTime添加六个月的时候不工作并返回一个异常。

我在试这个。

代码语言:javascript
复制
/** 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;
    }

我该如何解决这个问题?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-08-14 12:42:11

问题是,您正在向DateTime构造函数传递一个Month值,该值不在范围内。如果构造函数溢出到下一个更高的字段,则它不会滚动值。如果任何字段超出范围,它就会抛出一个异常,这里的14是肯定超出范围的[1, 12]

您可以简单地使用DateTime类中的plusMonths()方法来添加月份,而不是使用当前方法:

代码语言:javascript
复制
DateTime now = DateTime.now();
DateTime sixMonthsLater = now.plusMonths(6);

这将自动滚动月份值,如果它溢出。

票数 17
EN

Stack Overflow用户

发布于 2014-08-14 12:34:41

data.getMonthOfYear()将返回当前月份,即August,意思是8,但是您添加了6,这意味着mes变成了14,这不是一个有效的<代码>D9,因此结果为<代码>D10。

您可以使用DateTime类的加号方法

示例:

代码语言:javascript
复制
DateTime dt = new DateTime(); //will initialized to the current time
dt = dt.plusMonths(6); //add six month prior to the current date

Documentation

代码语言:javascript
复制
plusMonths(int months) 
      Returns a copy of this datetime plus the specified number of months.
票数 6
EN

Stack Overflow用户

发布于 2014-08-14 12:34:49

最简单的方法如下所示,使用plus方法向DateTime对象添加6个月的周期:

代码语言:javascript
复制
import org.joda.time.DateTime;
import org.joda.time.Months;

// ...

DateTime now = new DateTime();
DateTime sixMonthsLater = now.plus(Months.SIX);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25300140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档