How do I add x days to a date in Java?
For example, my date is 01/01/2012
, using dd/mm/yyyy
as the format.
Adding 5 days, the output should be 06/01/2012
.
Use the add() method of the calendar class to add days to the date. The add method() takes two parameter, i.e., calendar field and amount of time that needs to be added. Get the new date from the calendar and set the format of the SimpleDateFormat class to show the calculated new date on the screen.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar c = Calendar.getInstance(); c.setTime(new Date()); // Using today's date c.add(Calendar.DATE, 5); // Adding 5 days String output = sdf.format(c.getTime()); System.out.println(output);
With the Java 8 Date and Time API you can use the LocalDate
class.
LocalDate.now().plusDays(nrOfDays)
See the Oracle Tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With