Java examples to get the next day or the 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’s and yesterday’s dates based on the date of today.
1. Using LocalDate [Java 8]
Use LocalDate
‘s plusDays() and minusDays() method to get the next day and the 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. Using Date [Java 7]
Use Date
class constructor and pass the time in milliseconds. To get the time for yesterday, get the time for today and subtract the total milliseconds in a day.
Similarly, add the total milliseconds daily to get the time for the 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
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 the comments.
Happy Learning !!