Home >Java >javaTutorial >How to Verify a String\'s Date Format Conformance to a Given Pattern in Java?

How to Verify a String\'s Date Format Conformance to a Given Pattern in Java?

DDD
DDDOriginal
2024-10-30 02:21:29235browse

How to Verify a String's Date Format Conformance to a Given Pattern in Java?

Java: Verifying the Conformity of a String's Date Format to a Given Pattern

Understanding the Problem

You're given an input string and a desired date format. The goal is to determine if the string matches the specified format without actually converting it to a date.

Java Solution

One approach to this problem involves using SimpleDateFormat to parse the string according to the given format and comparing it to the original string. If they're not equal, the format is invalid.

Implementation

<code class="java">import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateFormatterValidator {

    public static boolean isValidFormat(String format, String value) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = sdf.parse(value);
            return value.equals(sdf.format(date));
        } catch (ParseException ex) {
            return false;
        }
    }

    public static void main(String[] args) {
        String format = "dd/MM/yyyy";
        String value1 = "20130925"; // Invalid
        String value2 = "25/09/2013"; // Valid

        System.out.println("isValidFormat(" + format + ", " + value1 + ") = " + isValidFormat(format, value1));
        System.out.println("isValidFormat(" + format + ", " + value2 + ") = " + isValidFormat(format, value2));
    }
}</code>

Output

isValidFormat(dd/MM/yyyy, 20130925) = false
isValidFormat(dd/MM/yyyy, 25/09/2013) = true

The above is the detailed content of How to Verify a String\'s Date Format Conformance to a Given Pattern in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn