This tutorial will show you how can you calculate either 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.

I will show you this calculation in Java language. If you need to calculate in PHP please read here https://www.roytuts.com/calculate-future-or-past-date-in-php/

The below source code shows how we can calculate future or past date in Java.

package com.roytuts.datecalc;

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

Future Date : 2015-12-02(yyyy-MM-dd)
Past Date : 2015-01-26(yyyy-MM-dd)

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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