Modify Dates of each object - MONTH, YEAR

Asked

Viewed 86 times

1

I have an application where I create a release of for example 400 real and before saving define the creation date and how many times I have to do. Then saved.

And at this point I save I add the launch to a Array release. If I did it twice, I have to pick the date that set and modify the dates, for example:

30/10 first instalment and then 30/11 to the second.

How can I modify this release dates?

1 answer

0


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

  • 1

    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.

  • 1

    http://answall.com/a/12568/28595

  • Blz, I’ll add on the answer

  • Okay, I think now it’s clearer and with the best options

  • 1

    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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.