What is the best way to parse a date in MM/DD/YY format and adjust it to the current / previous century?

后端 未结 5 1750
野趣味
野趣味 2020-12-11 02:37

One of our customers wants to be able to enter a date with only 2 digits for the year component. The date will be in the past, so we want it to work for the previous century

5条回答
  •  攒了一身酷
    2020-12-11 03:03

    SimpleDateFormat already does two-digit year parsing for you, using the two-letter ‘yy’ format. (It'll still allow four digits, obviously.)

    By default it uses now-80→now+20, so it's not exactly the same rule you propose, but it's reasonable and standardised (in the Java world at least), and can be overridden using set2DigitYearStart() if you want.

    DateFormat informat= new SimpleDateFormat("MM/dd/yy");
    DateFormat outformat= new SimpleDateFormat("MM/dd/yyyy");
    return outformat.format(informat.parse(dateString));
    

    In the longer term, try to migrate to ISO8601 date formatting (yyyy-MM-dd), because MM/dd/yy is approximately the worst possible date format and is bound to cause problems eventually.

提交回复
热议问题