java

How to add days to date in java

In this tutorial, we are going to see different ways to add days to a date in Java.

  • 1. Add days to a date using the Calendar class
  • 2. Add days to the current date using the Calendar class

 

Example 1: Add days to a date using the Calendar class:

In this example, we have a date “2020-05-20” and we would like to add days to it using the Calendar class.

import java.util.Calendar;
import java.text.*;


public class Main {
   public static void main(String args[]){

	String d1 = "2020-05-20";  
	System.out.println("Date before addition: "+d1);
	//Specify the date format corresponding to the date d1
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	Calendar cal = Calendar.getInstance();
	try{
	   //Set date
	   cal.setTime(sdf.parse(d1));
	}catch(ParseException e){
		e.printStackTrace();
	 }
	   
	//Number of days to add
	cal.add(Calendar.DAY_OF_MONTH, 3);  
	//Date after adding the days to the specified date
	String d2 = sdf.format(cal.getTime());  
	System.out.println("Date after addition: "+d2);
   }
}

Output:

Date before addition: 2020-05-20
Date after addition: 2020-05-23
 

Example 2: Add days to the current date using the Calendar class:
import java.text.*;
import java.util.*;

public class Main {
   public static void main(String args[]){
	   
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
	//Get the current date
	Calendar c = Calendar.getInstance();
	//Print the current date
	System.out.println("The current date: "+sdf.format(c.getTime()));
	   
	//Number of days to add
	c.add(Calendar.DAY_OF_MONTH, 3); 
	//Date after adding the days to the current date
	String d2 = sdf.format(c.getTime());  
	System.out.println("Date after addition: "+d2);
   }
}

Output:

The current date: 2020/03/19
Date after addition: 2020/03/22
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *