×

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between a particular point in time and a collection of calendar fields like DAY, MONTH, YEAR, HOUR, etc. The Similar interface is implemented by the Calendar class, which derives from the Object class.

How to declare a Calendar class in Java

Below is the syntax for declaring the calendar class:

abstract class Calendar extends Object implements Serializable, Cloneable, Comparable< Calendar>

With Java's Calendar class, we may add a single day or many days to the current Date or a supplied date. Let's examine the process for increasing the Date by a day.

How to add a given number of days to Date using calendar class

The steps below are used to operate the Calendar class to add days to the specified Date:

  1. We should first load all required courses and modules, including SimpleDateFormat and Calendar.
  2. Make a SimpleDateFormat and Calendar object. We interpret the data we want to add days using the objects created.
  3. Use the setTime() function of the calendar class to add the specified Date to the Calendar.
  4. We use the calendar classes add () method to add days to the Date. The calendar field and the amount of time that has to be added are the two parameters for the add method ().
  5. Take the obtained numerical Date from the Calendar and change the SimpleDateFormat class's default format to display it on the screen.

AddDaysExample1.java

// Package import section, all the required packages are imported  
import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.text.ParseException;  
class AddDaysExample1{  
    // Main method starts here 
    public static void main(String args[]){  
        //initializing the old Date as a string 
        String old = "2020-01-01";    
        System.out.println(old+" the data to which we have to add the days");  
        // creating the data format using the below method  
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
        // Creating the object to the calendar class to use the methods of it  
        Calendar obj = Calendar.getInstance();  
        try{  
           obj.setTime(format.parse(old));  
        }
        catch(ParseException e){  
            e.printStackTrace();  
         }  
        // using add() method of calendar class to add the days to the date 
        obj.add(Calendar.DAY_OF_MONTH, 5);  
        String dateAfter = format.format(obj.getTime());  
        //Date after adding five days to the old Date  
        System.out.println(dateAfter+" current date after adding 5 days to old date");  
    }  
}

OUTPUT

2020-01-01 the data to which we have to add the days
2020-01-06 current Date after adding 5 days to old Date

Using calendar class, counting the days to the current Date

The procedures for adding days to the present Date and a specified date are identical. In this instance, defining a date is not necessary. Here, we take the Date from the Calendar and add days to it afterwards.

Let's look at a specific scenario to comprehend further how we might extend the current Date by days.

AddDaysExample2.java

// Package import section, all the required packages are imported 
import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.text.ParseException;  
class AddDaysExample2{  
    // Main method starts here  
    public static void main (String args[]){  
        // creating the data format using the below method  
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
        // Creating the object to the calendar class to use the methods of it  
        Calendar obj = Calendar.getInstance();  
        System.out.println(format.format(obj.getTime())+" is the date before adding days");  
          
        // using add method of calendar class to add the days to the date  
        obj.add(Calendar.DAY_OF_MONTH, -3);  
        String dateAfter = format.format(obj.getTime());  
          
        //Date after adding 5 days to the old Date  
        System.out.println(dateAfter+" is the date after adding 3 days.");  
    }  
}  

OUTPUT

2020-01-01 the data to which we have to add the days
2020-01-06 current Date after adding 5 days to old Date

Without using a calendar class, adding days to a date

Including days in the Date is relatively simple without utilizing the Calendar class. We make use of Java. Time package's LocalDate class. The LocalDate class offers several ways to determine and alter the current Date.

Let's look at an illustration to understand better how the LocalDate class in Java can be used to compute dates.

AddDaysExample3.java

// Package import section, all the required packages are imported   
import java. time.LocalDate;   
class AddDaysExample3{  
    // Main method starts here  
    public static void main (String args[]){  
          
        // Loading the current and adding one day to the current Date.  
        LocalDate date1 = LocalDate.now().plusDays(1);  
        System.out.println(date1+" is a day after adding 1 day to the current date");  
            
        // Loading the current Date and adding five days to the current Date.  
        LocalDate date2 = LocalDate.now().plusDays(5);  
        System.out.println(date2+" is a day after adding 7 days to the current date");  
            
        // Specifying a particular date adding one day to it  
        LocalDate date3 = LocalDate.of(2019, 10, 14). plusDays(1);  
        System.out.println(date3+" is a day after adding 1 day to the define date");  
            
        // Specifying a particular date adding seven days to it  
        LocalDate date4 = LocalDate.of(2019, 10, 14). plusDays(7);  
        System.out.println(date4+" is a day after adding 7 days to the define date");  
    }  
}  

OUTPUT

2022-09-11 is a day after adding 1 day to the current Date
2022-09-15 is a day after adding 7 days to the current Date
2019-10-15 is a day after adding 1 day to the define date
2019-10-21 is a day after adding 7 days to the define date

Related Topics

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Dining Philosophers problem in Java

The Problem of the Dining Philosophers illustrates a concurrency issue involving the distribution of scarce resources among conflicting processes. Problem Statement Imagine a dining table with a circle in the middle and five...

3 minutes read.