Home > Enterprise >  to check the string is date or not in java
to check the string is date or not in java

Time:05-08

I want to check a string is date or not in java, also it should follow below condition 1:string should be in YYYYMMDD Format all other conditions it should throw error invalid date format. any one help with simple code

CodePudding user response:

You can do it like this. Do not use Date or any of its supported methods as they are obsolete. Not that this will also catch dates like Feb 30. If you don't want that, get rid of the strict parsing requirement in the formatter.

String[] test = {  "20220332", "20220515", "223322" };
try {
    for (String d : test) {
        System.out.printf("%s %s%n", d, validateDate(d) ? "Valid" : "Invalid");
    }
} catch (DateTimeParseException e) {
    System.out.println("Invalid Format");
}

prints

20220332 Invalid
20220515 Valid
223322 Invalid



static DateTimeFormatter dtf =
        DateTimeFormatter.ofPattern("uuuuMMdd")
     .withResolverStyle(ResolverStyle.STRICT);

public static boolean validateDate(String string) { 
    try {
        LocalDate.parse(string, dtf);
        return true;
    } catch (DateTimeParseException e) {
        return false;
    }
}

CodePudding user response:

You can use SimpleDateFormat:

DateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.setLenient(false);
try {
    sdf.parse(dateStr);
} catch (ParseException e) {
    System.out.println("Invalid date");
}
  •  Tags:  
  • java
  • Related