9

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.

root
  • 1,573
  • 3
  • 23
  • 38

4 Answers4

15

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;
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
mdm
  • 3,928
  • 3
  • 27
  • 43
  • Would be better to catch `IllegalArgumentException` rather than any old exception. – jhericks Jun 02 '17 at 00:00
  • FYI, the [Joda-Time](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [java.time](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 30 '17 at 22:27
9

This should work for you, I think (if you want to keep it simple).
You have to do setLenient(false) on a SimpleDateFormat.

public static boolean validateDate(String dateString){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setLenient(false);
    try {
        sdf.parse(dateString);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}
peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 30 '17 at 22:27
5

Use SimpleDateFormat

public boolean valiDate(String dateString){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setLenient(false);
    try {
        Date date = sdf.parse(dateString);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}
Aroniaina
  • 1,252
  • 13
  • 31
  • You were missing the `setLenient(false)` in the original answer. Anyway, +1 from me. – peter.petrov Oct 12 '15 at 13:50
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 30 '17 at 22:27
4

tl;dr

try {  … java.time.LocalDate.parse( input ) … } 
catch ( java.time.format.DateTimeParseException e ) { … }

java.time

The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2015-02-29" ) ;

To detect invalid inputs, trap for a DateTimeParseException.

String input = "2015-02-29";
try
{
    LocalDate ld = LocalDate.parse( input );
    System.out.println( "ld.toString():  " + ld ) ;
} catch ( DateTimeParseException e )
{
    // … handle exception
    System.out.println( e.getLocalizedMessage( ) );
}

Text '2015-02-29' could not be parsed: Invalid date 'February 29' as '2015' is not a leap year


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154