Java – Get Next and Previous Date

Java examples to get the next day or previous day for any given day. The example uses legacy java.util.Date class as well as java.time.LocalDate class from Java 8.

We can use this example code to calculate tomorrow and yesterday date base on the date of today.

1. java.time.LocalDate

Use LocalDate‘s plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.

private LocalDate findNextDay(LocalDate localdate)
{
	return localdate.plusDays(1);
}

private LocalDate findPrevDay(LocalDate localdate)
{
	return localdate.minusDays(1);
}

2. java.util.Date

Use Date class constructor and pass the time in milliseconds. To get the time for yesterday, get the time for today and subtract total milliseconds in a day.

Similarily, add total milliseconds in a day to get the time for next date.

private static final long MILLIS_IN_A_DAY = 1000 * 60 * 60 * 24;

private static Date findNextDay(Date date)
{
	return new Date(date.getTime() + MILLIS_IN_A_DAY);
}

private static Date findPrevDay(Date date)
{
	return new Date(date.getTime() - MILLIS_IN_A_DAY);
}

3. Complete Example to get next and previous date

import java.time.LocalDate;
import java.util.Date;

public class FindNextPrevDay 
{
	private static final long MILLIS_IN_A_DAY = 1000 * 60 * 60 * 24;
	
	public static void main(String[] args) 
	{
		Date today = new Date();
		
		System.out.println("Today     :: " + findNextDay(today));
		System.out.println("Next date :: " + findNextDay(today));
		System.out.println("Prev date :: " + findPrevDay(today));
		
		LocalDate todayDate = LocalDate.now();
		
		System.out.println("Today     :: " + todayDate);
		System.out.println("Next date :: " + findNextDay(todayDate));
		System.out.println("Prev date :: " + findPrevDay(todayDate));
	}
	
	private static Date findNextDay(Date date)
	{
		return new Date(date.getTime() + MILLIS_IN_A_DAY);
	}
	
	private static Date findPrevDay(Date date)
	{
		return new Date(date.getTime() - MILLIS_IN_A_DAY);
	}
	
	private static LocalDate findNextDay(LocalDate localdate)
	{
		return localdate.plusDays(1);
	}
	
	private static LocalDate findPrevDay(LocalDate localdate)
	{
		return localdate.minusDays(1);
	}
}

Program output:

Today     :: Sun May 03 19:49:34 IST 2020
Next date :: Sun May 03 19:49:34 IST 2020
Prev date :: Fri May 01 19:49:34 IST 2020

Today     :: 2020-05-02
Next date :: 2020-05-03
Prev date :: 2020-05-01

Drop me your questions in comments.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.