Java Add Number of Days to Current Date
Tags: Java Date
In this Java tutorial, we learn how to add a number of days to current Date value and return a new Date value in Java programming language.
How to add number of days to current Date in Java
In the following Java code, we learn how to add number of days to current Date value with these steps
- Instantiate current Date value using new Date() constructor.
- Using the Calendar.getInstance() method to create new Calendar object.
- Using the Calendar.setTime(Date date) to set current Date value to Calendar object.
- Using the Calendar.add(int field, int amount) method to add a number of days.
- Using the Calendar.getTime() to return the new Date value with number of days added.
AddDaysToCurrentDateExample.java
import java.util.Calendar;
import java.util.Date;
public class AddDaysToCurrentDateExample {
public static void main(String... args) {
int numberOfDays = 7;
// Add Number of Days to Current Date
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.DATE, numberOfDays);
Date newDate = calendar.getTime();
System.out.println("Number of days: " + numberOfDays);
System.out.println("Current Date: " + today);
System.out.println("New Date: " + newDate);
}
}
Number of days: 7
Current Date: Tue Sep 06 22:16:04 ICT 2022
New Date: Tue Sep 13 22:16:04 ICT 2022
Happy Coding 😊
Related Articles
Java Add Number of Days to Current LocalDate
Java Add Number of Days to Current LocalDateTime
Java Add Number of Days to Current OffsetDateTime
Java Add Number of Days to Current ZonedDateTime