Adding Years to a random date from Date class

后端 未结 9 1619
傲寒
傲寒 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 10:59

    Try java.util.Calendar type.

    Calendar cal=Calendar.getInstance();
    cal.setTime(yourDate.getTime());
    cal.set(Calendar.YEAR,n);
    
    0 讨论(0)
  • 2020-12-06 11:02

    If you need add one year a any date use the object Calendar.

    Calendar dateMoreOneYear = Calendar.getInstance();
    dateMoreOneYear.setTime(dateOriginal);
    dateMoreOneYear.add(Calendar.DAY_OF_MONTH, 365);
    
    0 讨论(0)
  • 2020-12-06 11:02

    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);
    
    0 讨论(0)
  • 2020-12-06 11:06

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

    Date date = new Date();
    date = DateUtils.addYears(date, int quantity = 1);
    
    0 讨论(0)
  • 2020-12-06 11:09

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

     System.out.println(LocalDate.now().plusYears(3).getYear());
    
    0 讨论(0)
  • 2020-12-06 11:16

    Try this....

    String s = new SimpleDateFormat("YYYY").format(new Date(random_date_in_long)); // 
    int i = Integer.parseInt(s)+n;
    
    0 讨论(0)
提交回复
热议问题