Java check valid date format - Java Date Validation

Overview

In this tutorial, we show you how to check valid date format using the java.text.SimpleDateFormat.

Java check valid date format

Using SimpleDateFormat to check valid date format

package com.jackrutorial;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class ValidDateExample {

 public static boolean isValidDate(String date, String dateFromat) {
  
  if(date == null)
   return false;
  
  if(dateFromat == null)
   return false;
  
  SimpleDateFormat format = new SimpleDateFormat(dateFromat);
  format.setLenient(false);
  
  try {
   format.parse(date.trim());
  } catch (ParseException pe) {
   pe.printStackTrace();
   return false;
  }
  
  return true;
 }
}

Testing with date format yyyy-MM-dd

package com.jackrutorial;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class ValidDateExample1 {

 public static void main(String[] args) {
  //testing with date1
  String date1 = "2018-07-15";
  String dateFromat = "yyyy-MM-dd";
  
  if(isValidDate(date1, dateFromat)) {
   System.out.println(date1 + " is valid date format");
  } else {
   System.out.println(date1 + " is invalid date format");
  }
  
  //testing with date2
  String date2 = "a2018-07-15";
  
  if(isValidDate(date2, dateFromat)) {
   System.out.println(date2 + " is valid date format");
  } else {
   System.out.println(date2 + " is invalid date format");
  }
 }

 public static boolean isValidDate(String date, String dateFromat) {
  
  if(date == null)
   return false;
  
  if(dateFromat == null)
   return false;
  
  SimpleDateFormat format = new SimpleDateFormat(dateFromat);
  format.setLenient(false);
  
  try {
   format.parse(date.trim());
  } catch (ParseException pe) {
   pe.printStackTrace();
   return false;
  }
  
  return true;
 }
}

Output

2018-07-15 is valid date format
java.text.ParseException: Unparseable date: "a2018-07-15"
 at java.text.DateFormat.parse(DateFormat.java:366)
 at com.jackrutorial.ValidDateExample1.isValidDate(ValidDateExample1.java:41)
 at com.jackrutorial.ValidDateExample1.main(ValidDateExample1.java:22)
a2018-07-15 is invalid date format
Previous Post
Next Post

post written by: