How to validate a String whether it is in YYYYMMDD format?
date, java, string
Solution
You can use SimpleDateFormat and Date, here is one solution -
private static final java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyyMMdd");
public static java.util.Date verifyInput(String input) {
if (input != null) {
try {
java.util.Date ret = sdf.parse(input.trim());
if (sdf.format(ret).equals(input.trim())) {
return ret;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
String[] dates = new String[] { "20141031",
"20130228", "20000229", "20000230" };
for (String str : dates) {
System.out.println(verifyInput(str));
}
}
Outputs
Fri Oct 31 00:00:00 EDT 2014
Thu Feb 28 00:00:00 EST 2013
Tue Feb 29 00:00:00 EST 2000
null
Problem
I have a string which is being passed to one of my method in the form of `YYYYMMDD` - ``` public static void verifyInput(String input) { } ``` Here input passed will be in this form "YYYYMMDD"; How do I validate whether `input` String which is passed in this form `YYYYMMDD` only? I just need to validate whether it is in `YYYYMMDD` this format.. I don't need to get the current date in this `YYYYMMDD` format and then compare it with `ss`. UPDATE:- I just need to validate the string input to see whether they are in this format `YYYYMMDD` Meaning if anyone is passing a String `hello` then it is not in this `YYYYMMDD` format.. And if anyone is passing this String `20130130` then this gets validated as it is in this `YYYYMMDD` format..