Is there anyway to validate if a given date(yyyy-MM-dd) is a valid date? It should handle leap year too. eg(2015-02-29) should be invalid. I'm retrieving the date as a string and putting it into a joda DateTime object.
Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.
Joda-Time is the most widely used date and time processing library, before the release of Java 8. Its purpose was to offer an intuitive API for processing date and time and also address the design issues that existed in the Java Date/Time API.
If your project still uses Joda-Time but would like to migrate to java. time then read on. The release of Java SE 8 included a new and improved standard Date and Time API commonly referred to as java. time (JSR-310).
You can create a Date object using the Date() constructor of java. util. Date constructor as shown in the following example. The object created using this constructor represents the current time.
The previous responses should be fine, but given that the OP specifically asked for a Joda-Time version, this alternative will also work:
@Test
public void test() {
String testDateOk = "2015-02-25"; // Normal date, no leap year
String testDateOk2 = "2016-02-29"; // Edge-case for leap year
String testDateWrong = "2017-02-29"; // Wrong date in a non-leap year
String testDateInvalid = "2016-14-29"; // plain wrong date
assertTrue(isValidDate(testDateOk));
assertTrue(isValidDate(testDateOk2));
assertFalse(isValidDate(testDateWrong));
assertFalse(isValidDate(testDateInvalid));
}
boolean isValidDate(String dateToValidate){
String pattern = "yyyy-MM-dd";
try {
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
fmt.parseDateTime(dateToValidate);
} catch (Exception e) {
return false;
}
return true;
}
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