How To Get Next and Previous Date In Java


Java8 LocalDate Example:

This example is to get the find next day or previous day for any provided day. Here in example will legacy java.util.Date class as well as java.time.LocalDate class from Java 8.

We will use this sample code to calculate yesterday and tomorrow date based on provided date (considering date as today).

1. Using java.util.Date:

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

2. Using java.time.LocalDate:

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. Explained complete Example:

import java.time.LocalDate;
import java.util.Date;
public class GetNextAndPrevDayUsingJava {
 private static final long MILLIS_IN_A_DAY = 1000 * 60 * 60 * 24;
 public static void main(String[] args) {
  Date today = new Date();
  logger.info("Today is :: " + findNextDay(today));
  logger.info("Next date is :: " + findNextDay(today));
  logger.info("Prev date is :: " + findPrevDay(today));
  LocalDate todayDate = LocalDate.now();
  logger.info("Today is :: " + todayDate);
  logger.info("Next date is :: " + findNextDay(todayDate));
  logger.info("Prev date is :: " + 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);
 }
}

 


%d bloggers like this: