Search code examples
javasimpledateformatdate-parsing

Possible values to be parsed using SimpleDateFormat


Sorry to ask if this is a duplicate question as I try to find solutions online but couldn't get a confirmed answer.

I would like to know the possible values that can be used to parse using SimpleDateFormat method in Java. For examples, the minimum and maximum values that can be parsed without error.

My date format is in yyyy-MM-dd

DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

1900-01-01 seems to be a valid one, but not 9999-12-31. The maximum date "valid" for me is 4637-11-25, any possible reason for this?


Solution

  • Avoid legacy date time classes

    You are using terribly flawed legacy date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.

    java.time.LocalDate

    For a date-only value, use LocalDate class.

    ISO 8601

    Your desired format of YYYY-MM-DD complies with the ISO 8601 standard for textual date-time formats. The java.time classes use these formats by default when parsing/generating text. So no need for you to define a custom formatting pattern.

    LocalDate ld = LocalDate.parse( "9999-12-31" ) ;
    

    See this code run at Ideone.com.

    From -999999999-01-01 to +999999999-12-31

    The minimum & maximum values are defined as constants: