View Full Version : [JAVA] GregorianCalendar e somma di mesi ad una data: metodo OK?
fbcyborg
16-03-2010, 10:32
Salve a tutti,
sto usando il seguente metodo per aggiungere i mesi ad una data:
public static Date sommaMesi(Date data, int mesi){
GregorianCalendar c = new GregorianCalendar();
c.setTime(data);
c.add(Calendar.MONTH,mesi);
return new Date(c.getTimeInMillis());
}
Che dite, può andar bene?
Chiedo conferma perché non sono molto sicuro, non vorrei incorrere in strani comportamenti visto che le scadenze sono importanti. Sembra funzionare comunque.
banryu79
16-03-2010, 11:45
Beh, il metodo add di java.util.GregorianCalendar è documentato così:
add
public void add(int field,
int amount)
Adds the specified (signed) amount of time to the given calendar field, based on the calendar's rules.
Add rule 1. The value of field after the call minus the value of field before the call is amount, modulo any overflow that has occurred in field. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.
Add rule 2. If a smaller field is expected to be invariant, but it is impossible for it to be equal to its prior value because of changes in its minimum or maximum after field is changed, then its value is adjusted to be as close as possible to its expected value. A smaller field represents a smaller unit of time. HOUR is a smaller field than DAY_OF_MONTH. No adjustment is made to smaller fields that are not expected to be invariant. The calendar system determines what fields are expected to be invariant.
Specified by:
add in class Calendar
Parameters:
field - the calendar field.
amount - the amount of date or time to be added to the field.
Throws:
IllegalArgumentException - if field is ZONE_OFFSET, DST_OFFSET, or unknown, or if any calendar fields have out-of-range values in non-lenient mode.
See Also:
Calendar.roll(int,int), Calendar.set(int,int)
Sei tu che sai se tale comportamento va bene nel tuo caso.
Comunque, puoi anche scrivere dei metodi di test dove, a partire da una o più date arbitrarie e note, eserciti il tuo metodo passandogli vari argomenti e verificando che il risultato prodotto sia uguale a quello che ti aspetti ;)
fbcyborg
16-03-2010, 11:50
Grazie, avevo letto più volte quel pezzo di documentazione che riporti, solo che non comprendevo bene l'utilizzo del metodo add e dei suoi parametri.
Ora quel metodo che ho scritto nel primo post, l'ho fatto a suon di tentativi, per questo chiedevo conferma.
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.