Adding days to a date in Java

JavaDate

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

java.time

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

LocalDate.now().plusDays(nrOfDays)

See the Oracle Tutorial.

Solution 3 - Java

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 2012);
cal.add(Calendar.DAY_OF_MONTH, 5);

You can also subtract days like this: Calendar.add(Calendar.DAY_OF_MONTH, -5);

Solution 4 - Java

Here is some simple code that prints the date five days from now:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 5);
System.out.println(dateFormat.format(c.getTime()));

Example output:

16/12/2021

See also: Calendar#add

Solution 5 - Java

If you're using Joda-Time (and there are lots of good reasons to - a simple, intuitive API and thread safety) then you can do this trivially:

new LocalDate().plusDays(5);

to add 5 days to today's date, for example.

EDIT: My current advice would be to now use the Java 8 date/time API

Solution 6 - Java

Simple, without any other API:

To add 8 days to the current day:

Date today = new Date();
long ltime = today.getTime()+8*24*60*60*1000;
Date today8 = new Date(ltime);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhari prasad View Question on Stackoverflow
Solution 1 - JavaswemonView Answer on Stackoverflow
Solution 2 - JavaMatthias BraunView Answer on Stackoverflow
Solution 3 - JavaPetr MensikView Answer on Stackoverflow
Solution 4 - Javauser3136058View Answer on Stackoverflow
Solution 5 - JavaBrian AgnewView Answer on Stackoverflow
Solution 6 - JavapraagmaView Answer on Stackoverflow