×

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java.

The Java calendar class offers methods for converting dates between a given moment in time and a variety of calendar fields, including MONTH, YEAR, HOUR, etc. It implements the Comparable, Serializable, and Cloneable interfaces and derives from the Object class.

We are unable to create an instance of it using a constructor because it is an abstract class. To create and implement a sub-class, we must instead utilize the static method Calendar.getInstance(). 

Calendar.getInstance(): return a Calendar instance based on the current time in the default time zone with the default locale.

Calendar.getInstance(TimeZone zone)

Calendar.getInstance(Locale aLocale)

Calendar.getInstance(TimeZone zone, Locale aLocale)

Decrementing the date in Java

To decrement the date in Java follow the given steps

Import the following package for Calendar class in Java

import java.util.Calendar ;

Firstly, create a Calendar object and display the current date

Calendar calendar = Calendar.getInstance() ;
System.out.println("Current Date = " + calendar.getTime()) ;

Now, let us decrement the date using the add() method and Calendar.DATE constant. Set a negative value since we are decrementing the date

calendar.add(Calendar.DATE, -3) ;

Example

Filename: Example.java

import java.util.Calendar;
public class Example {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance() ;
      System.out.println("Current Date = " + calendar.getTime()) ;
      // Decrementing date by 3
      calendar.add(Calendar.DATE, -3) ;
      System.out.println("Updated Date = " + calendar.getTime()) ;
   }
}

Output

How to increment and decrement date using Java

Incrementing the date in Java

import java.util.Calendar ;

First, create a Calendar object and display the current date

Calendar calendar = Calendar.getInstance() ;
System.out.println("Current Date = " + calendar.getTime()) ;

Now, let us increment the date using the add() method and Calendar.DATE constant

calendar.add(Calendar.DATE, 2) ;

Example

Filename: Example.java

import java.util.Calendar ;
public class Example {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance() ;
      System.out.println("Current Date = " + calendar.getTime()) ;
      // Incrementing date by 2
      calendar.add(Calendar.DATE, 2) ;
      System.out.println("Updated Date = " + calendar.getTime()) ;
   }
}

Output

How to increment and decrement date using Java

Filename: Example.java

import java.util.Calendar;
public class Example {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance() ;
      System.out.println("Current Date = " + calendar.getTime()) ;
      // Decrementing date by 5
      calendar.add(Calendar.DATE, -5) ;
      System.out.println("Date before 5 days= " + calendar.getTime()) ;


      // Incrementing date by 5
      calendar.add(Calendar.DATE, 10) ;
      System.out.println("Date after 5 days = " + calendar.getTime()) ;
   }
}

Output

How to increment and decrement date using Java

In this quick tutorial, you'll learn how to increment the days to the current date and time in Java.

Java Calendar api has a special add() method that increment the given number for the given unit.

Look at the below example that adds the 2 years 2 months 2 days to the current date.

Filename: AddDaysExample.java

import java.text.SimpleDateFormat ;
import java.util.Calendar ;
import java.util.Date ;


public class AddDaysExample {
public static void main(String[] args) {
// creating date in java
Date date = new Date() ;

// printing the date in readable format.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd") ;
String dateStr = dateFormat.format(date) ;
System.out.println("Current date : "+dateStr) ;

//creating calender instance 
Calendar calendar = Calendar.getInstance();
calendar.setTime(date) ;

// adding 2 years, months and date
calendar.add(Calendar.YEAR, 2) ;
calendar.add(Calendar.MONTH, 2) ;
calendar.add(Calendar.DATE, 2) ;

// getting the new date from the calendar
Date addedDate = calendar.getTime() ;

// printing the new date
String newDateinStr = dateFormat.format(addedDate) ;
System.out.println("New date after adding 2 years : "+newDateinStr) ;

}
}

Output

How to increment and decrement date using Java

Look at the below example that goes back to the 2 years 2 months 2 days to the current date.

Filename: Example.java

import java.text.SimpleDateFormat ;
import java.time.LocalDateTime ;
import java.time.ZoneId ;
import java.time.format.DateTimeFormatter ;
import java.util.Date ;


public class Example {
public static void main(String[] args) {
// date formats
String format = "yyyy-MM-dd hh:mm:ss" ;
SimpleDateFormat dateFormat = new SimpleDateFormat(format) ;


// Date format in java 8
DateTimeFormatter dateFormat8 = DateTimeFormatter.ofPattern(format) ;


// creating date in java
Date date = new Date() ;


// printing the date in readable format.
String dateStr = dateFormat.format(date) ;
System.out.println("Current date : " + dateStr) ;


// converting date to LocalDateTime
LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() ;
System.out.println("localDateTime : " + dateFormat8.format(localDateTime)) ;


localDateTime = localDateTime.minusYears(2) ;
localDateTime = localDateTime.minusMonths(2) ;
localDateTime = localDateTime.minusDays(2) ;


localDateTime = localDateTime.minusHours(2).minusMinutes(2).minusSeconds(2) ;


// converting LocalDateTime to Date
Date currentDateminus = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()) ;


// printing the new date
String newDateinStr = dateFormat.format(currentDateminus);
System.out.println("New date after going back 2 years : " + newDateinStr);


}
}

Output

How to increment and decrement date using Java

Related Topics

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating...

5 minutes read.

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

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

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.