javadatesimpledateformatdate-format2-digit-year

How to control SimpleDateFormat parse to 19xx or 20xx?


Is there a way to parse the following date string as July 23 1916 rather than July 23 2016?

System.out.println(new SimpleDateFormat("yy/MM/dd", Locale.US).parse("16/07/23"));

Solution

  • The Java Doc (http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) says:

    For parsing with the abbreviated year pattern ("y" or "yy"), SimpleDateFormat must interpret the abbreviated year relative to some century. It does this by adjusting dates to be within 80 years before and 20 years after the time the SimpleDateFormat instance is created. For example, using a pattern of "MM/dd/yy" and a SimpleDateFormat instance created on Jan 1, 1997, the string "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64" would be interpreted as May 4, 1964.

    The method SimpleDateFormat.set2DigitYearStart(Date) can be used to fix the year.