Java Strict vs. Lenient Date Parsing: What You Need to Know
2 min readFeb 21, 2025
Imagine a scenario where you added a date validator. It correctly rejects integer inputs by throwing an exception, but it still accepts valid dates even when they are not in the expected format.
The Problem: A Date Nightmare
Date Format used here is lenient and not strict.
package com;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* A utility class to validate and parse date strings.
*/
public class DateFormatChecker {
public static void main(String[] args) {
System.out.println("Date is " + validateDate("123") + "\n");
System.out.println("Date is " + validateDate("12-12-2025") + "\n");
System.out.println("Date is " + validateDate("2025-21-12") + "\n");
System.out.println("Date is " + validateDate("2025-12-24") + "\n");
}
private static Date validateDate(String dateStr) {
if (dateStr != null) {
try {
System.out.println("Date Format Set is yyyy-MM-dd");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(dateStr);
System.out.println("Date " + dateStr + " Parsed Successfully");
return date;
} catch (ParseException e) {
System.out.println("Exception -> " + e.getMessage());
}
}
return null;
}
}
Output:
The Hero:
We now use SimpleDateFormat
with setLenient(false)
to allow only valid dates. This strictly enforces the expected date format, rejecting any other formats.
dateFormat.setLenient(false); // Strict validation
Always remember to add dateFormat.setLenient(false)
when parsing dates for validation to prevent potential bugs in the future.
/**
* Validates and parses a given date string.
* <p>
* The method only accepts dates in the format {@code yyyy-MM-dd}. If the input
* does not match the expected format or is invalid, an exception message is
* printed and {@code null} is returned.
* </p>
*
* @param dateStr the date string to validate
* @return the parsed {@code Date} object if valid, otherwise {@code null}
*/
private static Date validateDate(String dateStr) {
if (dateStr != null) {
try {
System.out.println("Date Format Set is yyyy-MM-dd");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false); // Strict validation
Date date = dateFormat.parse(dateStr);
System.out.println("Date " + dateStr + " Parsed Successfully");
return date;
} catch (ParseException e) {
System.out.println("Exception -> " + e.getMessage());
}
}
return null;
}
Output:
Happy Coding :)