×

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

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

How to convert float to String in Java

How to convert float to String in java There are following methods to convert float to String: Convert using Float.toString(float) Convert using String.valueOf(float) Convert using Float.toString(float) The Float class has a static method that returns...

2 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.