java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to check if a string is a valid date?

The following code can be use to validate if a string contains a valid date information. The pattern of the date is defined by the SimpleDateFormat object. When the date is not valid a ParseException will be thrown.

package com.javacoderanch.example.util;

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

public class ValidDate {
    public static void main(String[] args) {
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy");

        //
        // Input to be parsed should strictly follow the defined date format
        // above.
        //
        format.setLenient(false);

        String date = "12/18/2007";
        try {
            format.parse(date);
        } catch (ParseException e) {
            System.out.println("Date " + date + " is not valid according to " +
                    ((SimpleDateFormat) format).toPattern() + " pattern.");
        }
    }
}