Add Days To Date Java Example
Chapter:
Date and Time
Last Updated:
08-08-2021 18:50:21 UTC
Program:
/* ............... START ............... */
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.text.ParseException;
public class AddDaysToDate {
public static void main(String args[]) {
String oldDate = "2021-02-16";
System.out.println("Date before Addition: " + oldDate);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
// Parsing and setting date to Calendar
try {
c.setTime(sdf.parse(oldDate));
} catch (ParseException e) {
e.printStackTrace();
}
// Adding 180 days to date.
c.add(Calendar.DAY_OF_MONTH, 180);
// Converting date to sting format.
String newDate = sdf.format(c.getTime());
// Displaying the new Date after addition of Days
System.out.println("New date after addition: " + newDate);
}
}
/* Output
Date before Addition: 2021-02-16
New date after addition: 2021-08-15
*/
// Program to add days to current date.
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class AddingDateToCurrentDate {
public static void main(String args[]) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
// This will give the current date and time.
Calendar cal = Calendar.getInstance();
System.out.println("Current Date: " + sdf.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, 180); // Will add 180 days
String newDate = sdf.format(cal.getTime());
System.out.println("New Date : " + newDate);
}
}
/* Output
Current Date: 2021/08/08
New Date : 2022/02/04
*/
/* ............... END ............... */
Notes:
-
In first program date is taking as string and we are paring the same using Calendar and SimpleDateFormat class.
- Add function in calendar class is used to add the days to calendar object.
- By using string format function calendar object has been again changed to string format and printing the same using System.out.println.
- Please refer the first program for more details.
- In second program Calendar.getInstance() will give the current date and same add function is used to add days to current date.
- As like the other program we used string format fuction to format the calendar instance to string format.
Tags
java program to add days to date, SimpleDateFormat , Calendar