Search code examples
javasimpledateformat

Converting String to Date is Formatting Year Incorrectly


I am trying to convert a string "05/09/20" to a Date format that will display the entire year.

This seems to be a simple enough process however SimpleDateFormat is returning the year as "0020"

Here is a sample code

import java.text.SimpleDateFormat;  
import java.util.Date;  
public class StringToDateExample1 {  
public static void main(String[] args)throws Exception {  
  SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
  String dateInString="05/09/20";
  Date date =  formatter.parse(dateInString);
  System.out.println(formatter.format(date));
}  
} 

Does anyone know why this is occurring?

Note: if I set simple date format to MM/dd/yy, it understands that the year is 2020


Solution

  • You need to parse with a formatter "MM/dd/yy" and write with a formatter "MM/dd/yyyy".

    This is because formatters simply shape the representation of an underlying date. Thus, if you want to read one format, and write a different one, you need to use one formatter to read into a date by converting a string of the format it expects into a date object (which does not have an intrinsic format), then pass that date to a different formatter which shapes it into the format you want to write in.

    So, you'll be doing the following:

    "05/09/20" (string of a certain format) 
    -A-> 
    {May Ninth 2020} (date, no specific format, it's just an object) 
    -B-> 
    "05/09/2020" (date expressed as a string in a different format)
    

    Note that B is not the reverse of A, therefore a single formatter cannot perform both.