Check a Given Date is Past, Today or Future’s Date in Java

Past, Present Or Future’s Date

In this example I am going to show you how to check if an input date is past date or today’s date or future date. For this example you should use at least Java version 8. Java 8 or higher version provides thread safe version of date time API classes that can be used safely in multi-threaded environment.

If you want to calculate the future or past date by adding or removing days to the input or given date then you can read the example on Future or Past date in Java or How to add or subtract days, weeks, months, years in Java 8 Date. In this example I will check only whether the data is future, past or today’s date in Java.

Prerequisites

Java 8 or higher version

Check Past, Future or Today

Java 8 onward date API provides isBefore(), isEqual(), isAfter() and these methods take an input date value which is then compared to another date value to check whether the input date is before, equal or after another date value.

public class DateFutureOrPastApp {

	public static void main(String[] args) {

		List<String> dates = Arrays.asList("2023-12-31", "2020-12-31", "2024-06-30", "2023-06-14", "2021-12-31",
				"2019-03-21", "2023-10-09", "2022-04-26", "2023-09-06");

		final String df = "yyyy-MM-dd";

		dates.forEach(d -> isDatePastTodayFuture(d, df));

	}

	public static void isDatePastTodayFuture(final String date, final String dateFormat) {
		LocalDate localDate = LocalDate.now(ZoneId.systemDefault());

		DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
		LocalDate inputDate = LocalDate.parse(date, dtf);

		if (inputDate.isBefore(localDate)) {
			System.out.println("The input date '" + date + "' is a past date");
		} else if (inputDate.isEqual(localDate)) {
			System.out.println("The input date '" + date + "' is a today's date");
		} else if (inputDate.isAfter(localDate)) {
			System.out.println("The input date '" + date + "' is a future date");
		}
	}

}

Running the above code will give you the following output:

The input date '2023-12-31' is a future date
The input date '2020-12-31' is a past date
The input date '2024-06-30' is a future date
The input date '2023-06-14' is a past date
The input date '2021-12-31' is a past date
The input date '2019-03-21' is a past date
The input date '2023-10-09' is a future date
The input date '2022-04-26' is a past date
The input date '2023-09-06' is a today's date

That’s all about checking the given date is past, future or today’s date.

Source Code

Download

Leave a Reply

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