Java date validation joda time

前端 未结 4 1708
失恋的感觉
失恋的感觉 2021-01-12 02:24

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 stri

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-12 03:06

    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?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • See How to use ThreeTenABP….

    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.

提交回复
热议问题