How to make DateFormat guess intended century?

前端 未结 2 1566
无人及你
无人及你 2020-12-19 03:13

I am trying to parse a String in \"dd-MM-yy\" format to a Date object. The problem is that it tries to guess the century for the date.

Whe

相关标签:
2条回答
  • 2020-12-19 03:59

    You can change the century it uses to interpret 2 digit data entry with the set2DigitYearStart() method.

    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
    String aDate = "03/17/40";
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(Calendar.YEAR, 2000);
    dateFormat.set2DigitYearStart(cal.getTime());
    System.out.println(dateFormat.get2DigitYearStart());
    System.out.println(dateFormat.parse(aDate));
    

    Will print March 17, 2040.

    0 讨论(0)
  • 2020-12-19 03:59

    From the documentation:

    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. During parsing, only strings consisting of exactly two digits, as defined by Character.isDigit(char), will be parsed into the default century. Any other numeric string, such as a one digit string, a three or more digit string, or a two digit string that isn't all digits (for example, "-1"), is interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the same pattern, as Jan 2, 3 AD. Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.

    It doesn't seem to mention any way to adjust the [-80; +20] range. I suspect your best bet is to expand the two-digit year into the four-digit form:

    datestr = datestr.replaceFirst("-(\\d{2})$", "-20$1");
    
    0 讨论(0)
提交回复
热议问题