Adding Years to a random date from Date class

Viewed 86433

Let's say I have this:

 PrintStream out = System.out;
 Scanner in = new Scanner(System.in);
 out.print("Enter a number ... ");
 int n = in.nextInt();

I have a random date, for example, 05/06/2015 (it is not a fixed date, it is random every time). If I want to take the 'year' of the this date, and add whatever 'n' is to this year, how do i do that?

None of the methods in the Date Class are 'int'.

And to add years from an int, 'years' has to be an int as well.

9 Answers

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.

Another package for doing this exists in org.apache.commons.lang3.time, DateUtils.

Date date = new Date();
date = DateUtils.addYears(date, int quantity = 1);

This will add 3 years to the current date and print the year.

 System.out.println(LocalDate.now().plusYears(3).getYear());

Try like this as well for a just month and year like (June 2019)

Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, n); //here n is no.of year you want to increase
SimpleDateFormat format1 = new SimpleDateFormat("MMM YYYY");
System.out.println(cal.getTime());

String formatted = format1.format(cal.getTime());
System.out.println(formatted);
Related