Adding Years to a random date from Date class

This question has long deserved a modern answer. And even more so after Add 10 years to current date in Java 8 has been deemed a duplicate of this question.

The other answers were fine answers in 2012. The years have moved on, today I believe that no one should use the now outdated classes Calendar and Date, not to mention SimpleDateFormat. The modern Java date and time API is so much nicer to work with.

Using the example from that duplicate question, first we need

private static final DateTimeFormatter formatter 
        = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");

With this we can do:

    String currentDateString = "2017-09-12 00:00:00";
    LocalDateTime dateTime = LocalDateTime.parse(currentDateString, formatter);
    dateTime = dateTime.plusYears(10);
    String tenYearsAfterString = dateTime.format(formatter);
    System.out.println(tenYearsAfterString);

This prints:

2027-09-12 00:00:00

If you don’t need the time of day, I recommend the LocalDate class instead of LocalDateTime since it is exactly a date without time of day.

    LocalDate date = dateTime.toLocalDate();
    date = date.plusYears(10);

The result is a date of 2027-09-12.

Question: where can I learn to use the modern API?

You may start with the Oracle tutorial. There’s much more material on the net, go search.


You need to convert the Date to a Calendar.

Calendar c = Calendar.getInstance();
c.setTime(randomDate);
c.add(Calendar.YEAR, n);
newDate = c.getTime();

You can manipulate the Year (or other fields) as a Calendar, then convert it back to a Date.

Tags:

Java