Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java date validation joda time

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.

like image 967
root Avatar asked Oct 12 '15 13:10

root


People also ask

Is Joda-time followed in Java 8?

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.

What is Joda Date time?

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.

What is the replacement of Joda-time Library in Java 8?

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).

How do you create a date and time object in Java?

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.


1 Answers

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;
}
like image 121
mdm Avatar answered Oct 22 '22 05:10

mdm