Add month with JodaTime?

10,400

Solution 1

The issue is, you're passing a month value to DateTime constructor, which is not in range. The constructor doesn't do rolling of values if it overflows to next higher field. It throws an exception if any field is out of range, here month is 14 which is certainly out of range [1, 12].

Rather than using the current approach, you can simply use plusMonths() method from DateTime class to add months:

DateTime now = DateTime.now();
DateTime sixMonthsLater = now.plusMonths(6);

This will automatically roll the month value if it overflows.

Solution 2

The data.getMonthOfYear() will return the current month which is August means 8 but you add 6 that means mes becomes 14 which is not a valid MonthOfYear thus result to IllegalFieldValueException: Value 14 .

You can use the plus methods of the DateTime class

sample:

DateTime dt = new DateTime(); //will initialized to the current time
dt = dt.plusMonths(6); //add six month prior to the current date

Documentation:

plusMonths(int months) 
      Returns a copy of this datetime plus the specified number of months.

Solution 3

The easiest way to do it is like this, by adding a period of 6 months to a DateTime object using the plus method:

import org.joda.time.DateTime;
import org.joda.time.Months;

// ...

DateTime now = new DateTime();
DateTime sixMonthsLater = now.plus(Months.SIX);
Share:
10,400
FernandoPaiva
Author by

FernandoPaiva

I'm from Brazil

Updated on June 04, 2022

Comments

  • FernandoPaiva
    FernandoPaiva about 2 years

    I'm trying add month with JodaTime. I have a payment plan with some months, example: one month, two month, three month and six month.

    When I add six month at DateTime doesn't work and return an exception.

    I'm trying this.

    /** 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;
        }
    

    How to I can solve this problem ?

  • Robby Cornelissen
    Robby Cornelissen almost 10 years
    Note that DateTime objects are immutable. Your call to dt.plusMonths(6); does not affect the dt object. You need to capture the result using, e.g. dt = dt.plusMonths(6);
  • Robby Cornelissen
    Robby Cornelissen about 8 years
    @JeffMercado The reason being?
  • Jeff Mercado
    Jeff Mercado about 8 years
    Ah, sorry, I misunderstood what the constants in the Months class represented. There just happened to be 12 constants defined, I thought they each represented the month number. (the reverse of what you might think Months.JANUARY might be)