Search code examples
javadatedatetimesimpledateformatdate-format

Convert two digit year to four digits and also support one or two digit month


I want to convert two digits year to four digits and also it is possible to come 4 digits

        final Integer year = 2020;
        final Integer month = 12;
        final DateFormat originalFormat = new SimpleDateFormat("MMyy", Locale.US);
        final Date monthAndYear = originalFormat.parse(month + String.valueOf(year));
        final DateFormat formattedDate = new SimpleDateFormat("yyyy-MM", Locale.US);

        System.out.println(formattedDate.format(monthAndYear));

This code fails if the input is 2-2020, which not parsing one digit month.

I want to pass the code by below conditions


        year       | month       || expeected
        2020       | 12          || "2020-12"
        30         | 2           || "2030-02"
        41         | 05          || "2041-05"


Solution

  • You can use YearMonth for this like so:

    final DateTimeFormatter YEAR_FORMAT = DateTimeFormatter.ofPattern("[yyyy][yy]");
    YearMonth yearMonth = YearMonth.of(
            Year.parse(year, YEAR_FORMAT).getValue(),
            month);
    

    Note: The year should be a String

    Outputs:

    2020-12
    2030-02
    2041-05