×

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 Integer max() method

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

2 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

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

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.