Adding Years to a random date from Date class

后端 未结 9 1620
傲寒
傲寒 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:18

    The Date class will not help you, but the Calendar class can:

    Calendar cal = Calendar.getInstance();
    Date f;
    ...
    cal.setTime(f);
    cal.add(Calendar.YEAR, n); // Where n is int
    f = cal.getTime();
    

    Notice that you still have to assign a value to the f variable. I frequently use SimpleDateFormat to convert strings to dates.

    Hope this helps you.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-06 11:23

    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.

    0 讨论(0)
提交回复
热议问题