Thursday, 23 May 2019

Java: Check whether given date is valid or not


Following function returns true, if the given date is valid, else false.

public static boolean isDateValid(String date) {
         try {
                  DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
                  dateFormat.setLenient(false);
                  dateFormat.parse(date);
                  return true;
         } catch (ParseException e) {
                  return false;
         }
}

App.java
package com.sample.app;

import java.io.FileNotFoundException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class App {
 private static final String DATE_FORMAT = "dd-MM-yyyy";

 public static boolean isDateValid(String date) {
  try {
   DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
   dateFormat.setLenient(false);
   dateFormat.parse(date);
   return true;
  } catch (ParseException e) {
   return false;
  }
 }

 public static void main(String args[]) throws FileNotFoundException {

  boolean isValid = isDateValid("32-1-2019");
  System.out.println("Is \"32-1-2019\" valid ? " + isValid);

  isValid = isDateValid("31-1-2019");
  System.out.println("Is \"31-1-2019\" valid ? " + isValid);

 }
}

Output
Is "32-1-2019" valid ? false
Is "31-1-2019" valid ? true


You may like

Previous                                                    Next                                                    Home

No comments:

Post a Comment