×

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

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

What is advance Java?

The definition of advance inside the dictionary refers to a forward motion, development, or progress, and the definition of enhancing is something that improves things. To become experts in that...

3 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Java Thread class

Thread class The thread represents a part of the process. Every process can have multiple associated threads in which every thread may execute the same or different job. By default, each thread assigns...

16 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.