I am currently writing a validation method in Java to check if a string is in one of a few different format to be changed into a date.
The formats that I want it to accept are the following: MM/DD/YY , M/DD/YY, MM/D/YY, and M/D/YY.
I was testing the first format and every time it was telling me it was not valid even when I entered in a valid date.
Here is what my current code looks like:
public class IsDateFormatValid
{
public boolean isValid(String date)
{
boolean result = true;
if(date.length()>8||date.length()<6)
{
result= false;
}
if(date.length()==8)
{
if((Character.toString(date.charAt(2))!= "/")||(Character.toString(date.charAt(5))!="/"))
{
result=false;
}
}
if(date.length()==7)
{
if((Character.toString(date.charAt(2))!="/"&&Character.toString(date.charAt(1))!="/") ||(Character.toString(date.charAt(3))!="/"&&Character.toString(date.charAt(4))!= "/"))
{
result=false;
}
}
return result;
}
}
I still need to put in the conditions for the last format case. I did a debug method and saw that the part that always returning false was the line that said: if((Character.toString(date.charAt(2))!= "/")||(Character.toString(date.charAt(5))!="/"))
The main point of this question is trying to check it against multiple formats not just a singular one how most other questions on here ask about.
To validate a string for alphabets you can either compare each character in the String with the characters in the English alphabet (both cases) or, use regular expressions.
matcher(str). matches() .
You can use the Pattern. matches() method to quickly check if a text (String) matches a given regular expression. Or you can compile a Pattern instance using Pattern. compile() which can be used multiple times to match the regular expression against multiple texts.
You might want to iterate through possible formats, like this:
EXAMPLE:
private static String[] date_formats = {
"yyyy-MM-dd",
"yyyy/MM/dd",
"dd/MM/yyyy",
"dd-MM-yyyy",
"yyyy MMM dd",
"yyyy dd MMM",
"dd MMM yyyy",
"dd MMM yyyy"
};
/**
* A brute-force workaround for Java's failure to accept "any arbitrary date format"
*/
public static Date tryDifferentFormats (String sDate) {
Date myDate = null;
for (String formatString : date_formats) {
try {
SimpleDateFormat format = new SimpleDateFormat(formatString);
format.setLenient(false);
myDate = format.parse(sDate);
break;
}
catch (ParseException e) {
// System.out.println(" fmt: " + formatString + ": FAIL");
}
}
return myDate;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With