How To Add days to Date in Java

In this tutorial, we will be going to solve and understand the problem how to add days to Date in Java.

We will be looking forward to which all packages to import and how it is implemented.

How to Add Days to Date in Java

In this tutorial of solving the problem of how to add days to a date in Java, we are importing initially “java.util.Calendar” package.

This is basically the “Calendar” class which basically provides us methods for converting date between a specific instant and set of Calendar fields.

Some of methods of this package include getWeekYear(), getTimeZone(),etc.

Also, we used “java.text.SimpleDateFormat“, which provides various methods to format date and time in java.

Inside the main block, we created an instance of “SimpleDateFormat for formatting the date in a desired particular pattern.

Also, we created an object of class Calendar with the help of method Calendar.getInstance.

This helps in getting the input of the date from the system.

Also, read:

This method returns the calendar.

Now, we displayed the current date in a formatted manner.

Our objective here is to add days to a date, for which we are provided with a method to add a number of days to a constraint of date.

We passed the no. of the day of the month and along with we passed no. of days we want to add to it.

Now simply formatting the updated result of date, we can display the added days result of date.

Below is the Program for the above problem in java for Topic “How To add days in a date”:

import java.text.SimpleDateFormat;
import java.util.Calendar;
class Caladd
  public static void main(String args[])
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
  Calendar cal = Calendar.getInstance();
  System.out.println("Current Date: "+sdf.format(cal.getTime()));
  cal.add(Calendar.DAY_OF_MONTH, 30);  
  String newDate = sdf.format(cal.getTime());  
  System.out.println("Date after Addition: "+newDate);

After the successful compilation of the above program, we will be getting our expected result with added days to a date in Java.

Below is the output for the above program:

How To Add days to Date in Java

Leave a Reply

Your email address will not be published. Required fields are marked *