-1

What is the best way to make operation on a util.date Object in java.

For example: I have a date 2018.10.02 and i want to add 3 Month to this date and to get another util.date object with the good date.

The same with adding or substracting day, years or hours...

Thanks

shmoolki
  • 1,551
  • 8
  • 34
  • 57
  • 5
    the best way is to use the new Date types – Stultuske Oct 02 '18 at 13:24
  • using Calendar class. look at [this](https://stackoverflow.com/a/6186006/3627279) – Joe Oct 02 '18 at 13:27
  • I saw this post https://stackoverflow.com/a/23438360/3767862 but i want to get a Date object and not a LocalDate – shmoolki Oct 02 '18 at 13:28
  • Always search Stack Overflow before posting. Specifically: Search for [`LocalDate` class with its *plus*](https://duckduckgo.com/?q=site%3Astackoverflow.com+java+LocalDate+plus&t=osx&ia=web) & *minus* methods. – Basil Bourque Oct 14 '18 at 23:47

2 Answers2

2

You can use java.time package since java8, for example:

Date date = new Date();

Instant instant = Instant.ofEpochMilli(date.getTime());

ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
zonedDateTime = zonedDateTime.plusMonths(3);

Date afterThreeMonth = Date.from(zonedDateTime.toInstant())
xingbin
  • 27,410
  • 9
  • 53
  • 103
2

New class java.time.LocalDate is better for that kind of operations:

    LocalDate date = LocalDate.parse("2018-10-02").plusMonths(3);
Benoit
  • 5,118
  • 2
  • 24
  • 43