How do I get pattern string of a SimpleDateFormat?

To format a java.util.Date object we use the SimpleDateFormat class. To get back the string pattern that were used to format the date we can use the toPattern() method of this class.

package org.kodejava.example.text;

import java.text.SimpleDateFormat;
import java.util.Date;

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

        // Gets a pattern string describing this date format used by the
        // SimpleDateFormat object.
        String pattern = format.toPattern();

        System.out.println("Pattern = " + pattern);
        System.out.println("Date    = " + format.format(new Date()));

The result of the program will be as follow:

Pattern = EEEE, dd/MM/yyyy
Date    = Monday, 16/04/2018

How do I 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 java.text.SimpleDateFormat object. When the date is not valid a java.text.ParseException will be thrown.

package org.kodejava.example.text;

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

public class DateValidation {
    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.

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

The result of the above date validation code is:

Date 29/18/2017 is not valid according to dd/MM/yyyy pattern.