Solution 1 (Recommended): In the Java 8 you can use the new API JSR-310
inspired by Joda-Time
. This library can also be downloaded to Java 7 here:
LocalDateTime.from(data.toInstant()).plusDays(1);
Solution 2: You can also use the library Joda-Time
, which greatly facilitates the use of date and time elements in Java:
DateTime dataJoda = new DateTime(data);
dataJoda = dataJoda.plusMonths(1);
Solution 3: Use the class Calendar
as follows, where the variable data
is a Date
with the defined date:
Calendar c = Calendar.getInstance();
c.setTime(data);
c.add(Calendar.MONTH, 1);
data = c.getTime();
This solution is not recommended following the extensive explanation given in this topic Difference between Date, sql. Date and Calendar, which boils down to:
DON’T USE ANY OF THOSE CLASSES. They are full of flaws -- I would need an entire answer just to talk about it -- and there are much superior alternatives.
Calculation method
Using the JSR-310
the implementation would be similar to the following example:
private List<LocalDateTime> calcularDatas(LocalDateTime dataBase, Integer quantidade) {
List<LocalDateTime> resultado = new ArrayList<>();
Integer indice;
for (indice = 0; indice < quantidade; indice++) {
resultado.add(dataBase.plusMonths(indice));
}
return resultado;
}
Reference: How to add one day to a date?, Difference between Date, sql. Date and Calendar
Using Bashar for this is a bad option. No doubt it either uses joda time for verses smaller than 8 from java, or uses the java.time package for more recent versions.
– user28595
http://answall.com/a/12568/28595
– user28595
Blz, I’ll add on the answer
– Sorack
Okay, I think now it’s clearer and with the best options
– Sorack
I used the Calendar class because it is simpler to deal with at the moment. I’m starting in java and don’t have daily practice yet, but I’ll study what I was recommended, JSR-310.
– Rafael Blum