Introduction
This tutorial will show you how you can calculate future or past date in Java. The calculation is done on future date from a particular date to “plus a number of given days” or past date from a particular date to “minus a number of given days”.
Future or past date calculation may be required for various purposes such as to calculate the age of a person on future date or on past date.
Related Posts:
- https://roytuts.com/calculate-future-or-past-date-in-php/
- Add or subtract days, weeks, months, years on Java 8 Date
Java Source Code
The below source code shows how we can calculate future or past date in Java.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateCalculation {
private static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* @param args
*/
public static void main(String[] args) {
String date = "2015-02-25"; //date from which a next or past date will be calculated
String futureDate = addDaysToDate(date, "280"); //get date after adding 280 days to the above date
System.out.println("Future Date : " + futureDate + "(" + DATE_FORMAT
+ ")");
String pastDate = subtractDaysFromDate(date, "30"); //get past date after subtracting 30 days from the above date
System.out.println("Past Date : " + pastDate + "(" + DATE_FORMAT + ")");
}
/**
*
* @param date
* @param days
* @return string
*/
private static String addDaysToDate(String date, String days) {
Calendar c = Calendar.getInstance();
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
try {
Date myDate = df.parse(date.trim());
c.setTime(myDate);
c.add(Calendar.DATE, Integer.parseInt(days));
} catch (ParseException e) {
e.printStackTrace();
}
String toDate = df.format(c.getTime());
return toDate;
}
/**
*
* @param date
* @param days
* @return string
*/
private static String subtractDaysFromDate(String date, String days) {
Calendar c = Calendar.getInstance();
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
try {
Date myDate = df.parse(date.trim());
c.setTime(myDate);
c.add(Calendar.DATE, (Integer.parseInt(days) * -1));
} catch (ParseException e) {
e.printStackTrace();
}
String toDate = df.format(c.getTime());
return toDate;
}
}
Output
On executing the above Java class you will see below output:
Future Date : 2015-12-02(yyyy-MM-dd)
Past Date : 2015-01-26(yyyy-MM-dd)
Thanks for reading.