javadatedate-conversiondate-parsing2-digit-year

Error converting date with two digits for the Year field


// input format: dd/MM/yy
SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yy");
// output format: yyyy-MM-dd
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(formatter.format(parser.parse("12/1/20"))); // 0020-11-01

I am using the above code but it is giving me year as '0020' instead of '2020'.


Solution

  • Use java.time for this:

    public static void main(String[] args) {
        String dateString = "12/1/20";
        LocalDate localDate = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd/M/yy"));
        System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
    }
    

    The output is

    2020-01-12
    

    Pay attention to the amount of M in the patterns, you cannot parse a String that contains a single digit for a month using a double M here.