×

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a certain point in time and a collection of calendar fields like DAY, MONTH, YEAR, HOUR, etc. Calendar, a class that also descends from an Object, implements the Comparable interface.

The Calendar class's declaration

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

Using Java's Calendar class, we may modify a specified date or the current date by adding either a single day or a number of days. Let's examine how we might extend the date by days.

1. Using the Calendar class, add Days to the specified Date

The following procedures are used to extend the specified date by days using the Calendar class:

  • Including SimpleDateFormat and Calendar, we import all required classes and packages.
  • Instances of SimpleDateFormat and Calendar should be created. These instances allow us to parse the date to which we need to add days.
  • Use the setTime() function of the calendar class to add the specified date to the calendar.
  • Use the add() function of the calendar class to extend the date by a day. The add method's two parameters are the calendar element and the amount of time that must be added ().
  • Take the newly calculated date from the calendar as well as change the SimpleDateFormat class's default format to display it on the screen.

Example program

import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.text.ParseException;  
class Date {  
    public static void main(String args[]){  
        String dateBefore = "2022-08-11";    
System.out.println(dateBefore+" is the date before adding the  days");  
SimpleDateFormatsdf = new SimpleDateFormat("yyyy-MM-dd");  
        Calendar cal = Calendar.getInstance();  
try{
cal.setTime(sdf.parse(dateBefore));  
}catch(ParseException e){  
e.printStackTrace();  
         }  
cal.add(Calendar.DAY_OF_MONTH, 3);  
        String dateAfter = sdf.format(cal.getTime());  
System.out.println(dateAfter+" is the date after adding the 3 days.");  
    }  
}  

Output

2022-08-11 is the date before adding 4 the  days
2022-08-14 is the date after adding the 4 days.

2. Using the Calendar class, add days to the current date.

The procedures for adding days to a current date and a given date are identical. In this instance, defining a date is not necessary. Here, we take a date from the calendar and then add days to it.

Example program

import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.text.ParseException;  
class Date { 
    public static void main(String args[]) {  
SimpleDateFormatsdf = new SimpleDateFormat("yyyy-MM-dd");  
        Calendar cal = Calendar.getInstance();  
System.out.println(sdf.format(cal.getTime())+" is the date before the adding days");  
cal.add(Calendar.DAY_OF_MONTH, -4);  
        String dateAfter = sdf.format(cal.getTime());  
System.out.println(dateAfter+" is the date after adding the 3 days.");  
    }  
}     

The output of the above program

2022-11-25 is the date before the adding days
2022-11-21 is the date after adding the 3 days.

3. Without utilizing the Calendar class, date addition

Including days in a date without using the Calendar class is a rather simple process.

We make use of the Java.time package's LocalDate class. The LocalDate class offers a number of ways to determine and alter the current date.

Example program

class Date 
 {  
    public static void main(String args[])
    {  
LocalDate newDate1 =  LocalDate.now().plusDays(2);  
System.out.println(newDate1+" is a day after adding a 4 day to the current date"); 
LocalDate newDate2 =  LocalDate.now().plusDays(3);  
System.out.println(newDate2+" is a day after adding a  8 day to the current date");  
LocalDate newDate3 = LocalDate.of(2020, 11, 15).plusDays(1);  
System.out.println(newDate3+" is a day after adding 1 day to the defined date");  
LocalDate newDate4 = LocalDate.of(2020, 11, 15).plusDays(7);  
System.out.println(newDate4+" is a day after adding 7  a day to the defined date");  
    }  
}   

Output

2022-11-27 is a day after adding a 4-day to the current date
2022-11-28 is a day after adding an 8 day to the current date
2020-11-16 is a day after adding 1 day to the defined date
2020-11-22 is a day after adding 7 a day to the defined date

Example 2:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Date {
    private static final DateFormatdateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    public static void main(String[] args) {
        Date currentDate = new Date();
System.out.println(dateFormat.format(currentDate));
        Calendar c = Calendar.getInstance();
c.setTime(currentDate);
c.add(Calendar.YEAR, 2);
c.add(Calendar.MONTH, 3);
c.add(Calendar.DATE, 2); 
c.add(Calendar.HOUR, 3);
c.add(Calendar.MINUTE, 2);
c.add(Calendar.SECOND, 2);
        Date currentDatePlusOne = c.getTime();
System.out.println(dateFormat.format(currentDatePlusOne));
    }
}

Output

2022/11/25 09:31:012023/12/26 10:32:02

Related Topics

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 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.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 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.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.