Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Tuesday, January 22, 2019

Java 8: How to check date is valid future date.

Check if a date is a valid future date. 

As a developer we come across many scenarios where we want to validate the user selected date is the correct future date.  

Java 8 provides many useful classes and methods under Date Time API. Below code snippet checks if the date is a valid future date. 



        /**
  * DateTime function which checks for the valid future date.
  * 
  * @author ajain5
  * @param futureDate
  *            : in dd-mm-yyyy or dd/mm/yyyy format
  * @return true if futureDate isAfter currentDate
  */
 public boolean isValidFutureDate(String futureDate) {
  String date[] = futureDate.split("[\\/-]");
  int day = Integer.parseInt(date[0]);
  int month = Integer.parseInt(date[1]);
  int year = Integer.parseInt(date[2]);

  LocalDate today = LocalDate.now();
  return today.isBefore(LocalDate.of(year, month, day));

 }


You can test the above code using below driver program. 


System.out.println(new Ti().isValidFutureDate(args[0]));

Response after running the above program :


Current date : 22-01-2019

The above program was tested on 22-Jan-2019 .

No comments: