Java 日期验证 joda 时间

Java date validation joda time

是否有验证给定日期 (yyyy-MM-dd) 是否有效的日期? 它也应该处理闰年。例如(2015-02-29)应该是无效的。 我正在检索字符串形式的日期并将其放入 joda DateTime 对象中。

使用简单日期格式

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;
    }
}

我认为这应该适合你(如果你想保持简单的话)。
您必须在 SimpleDateFormat 上执行 setLenient(false)

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;
    }
}

之前的回复应该没问题,但考虑到 OP 特别要求 Joda-Time 版本,这个替代方案也可以:

@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;
}

tl;博士

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

java.time

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

LocalDate class 表示没有时间和时区的仅日期值。

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

要检测无效输入,陷阱 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


关于java.time

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.

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

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

从哪里获得java.time classes?

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.