BAEL-3045 Validate Date
Check if a string contains valid date
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.date.validation;
|
||||
|
||||
public interface DateValidator {
|
||||
public boolean isValid(String dateStr);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.date.validation;
|
||||
|
||||
import org.apache.commons.validator.GenericValidator;
|
||||
|
||||
public class DateValidatorUsingApacheValidator implements DateValidator {
|
||||
|
||||
@Override
|
||||
public boolean isValid(String dateStr) {
|
||||
return GenericValidator.isDate(dateStr, "yyyy-MM-dd", true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.date.validation;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
public class DateValidatorUsingDateFormat implements DateValidator {
|
||||
private String dateFormat;
|
||||
|
||||
public DateValidatorUsingDateFormat(String dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(String dateStr) {
|
||||
DateFormat sdf = new SimpleDateFormat(this.dateFormat);
|
||||
sdf.setLenient(false);
|
||||
try {
|
||||
sdf.parse(dateStr);
|
||||
} catch (ParseException e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.date.validation;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
|
||||
public class DateValidatorUsingDateTimeFormatter implements DateValidator {
|
||||
private DateTimeFormatter dateFormatter;
|
||||
|
||||
public DateValidatorUsingDateTimeFormatter(DateTimeFormatter dateFormatter) {
|
||||
this.dateFormatter = dateFormatter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(String dateStr) {
|
||||
try {
|
||||
this.dateFormatter.parse(dateStr);
|
||||
} catch (DateTimeParseException e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.date.validation;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
|
||||
public class DateValidatorUsingLocalDate implements DateValidator {
|
||||
private DateTimeFormatter dateFormatter;
|
||||
|
||||
public DateValidatorUsingLocalDate(DateTimeFormatter dateFormatter) {
|
||||
this.dateFormatter = dateFormatter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(String dateStr) {
|
||||
try {
|
||||
LocalDate.parse(dateStr, this.dateFormatter);
|
||||
} catch (DateTimeParseException e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user