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.
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.
<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>
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!