Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding days to a date in Java [duplicate]

Tags:

java

date

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.

like image 250
hari prasad Avatar asked Aug 23 '12 08:08

hari prasad


People also ask

How do I add days to a date in Java?

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.


2 Answers

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); 
like image 122
swemon Avatar answered Oct 09 '22 01:10

swemon


java.time

With the Java 8 Date and Time API you can use the LocalDate class.

LocalDate.now().plusDays(nrOfDays) 

See the Oracle Tutorial.

like image 25
Matthias Braun Avatar answered Oct 09 '22 01:10

Matthias Braun