Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Years to a random date from Date class

Tags:

java

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.

like image 963
Shawn Avatar asked Sep 11 '25 12:09

Shawn


1 Answers

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.

like image 172
Jon Lin Avatar answered Sep 14 '25 04:09

Jon Lin