Adding Years to a random date from Date class

后端 未结 9 1629
傲寒
傲寒 2020-12-06 10:19

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();
         


        
9条回答
  •  醉梦人生
    2020-12-06 11:20

    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.

提交回复
热议问题