How to control SimpleDateFormat parse to 19xx or 2

2019-04-18 01:16发布

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"));

4条回答
【Aperson】
2楼-- · 2019-04-18 01:38

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.

查看更多
成全新的幸福
3楼-- · 2019-04-18 01:50

May be you are looking for this.

    Calendar cal = Calendar.getInstance();
    cal.set( Calendar.YEAR, 1900 );
    SimpleDateFormat format = new SimpleDateFormat( "yy/MM/dd", Locale.US );
    format.set2DigitYearStart( cal.getTime() );
    System.out.println( format.parse( "16/07/23" ) );
查看更多
Fickle 薄情
4楼-- · 2019-04-18 01:51

If I understand your question then yes,

SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd", Locale.US);
Calendar cal = Calendar.getInstance(Locale.US);
cal.set(1900, 0, 1);
sdf.set2DigitYearStart(cal.getTime());
System.out.println(sdf.parse("16/07/23"));

Per the SimpleDateFormat.set2DigitYearStart(Date) javadoc,

Sets the 100-year period 2-digit years will be interpreted as being in to begin on the date the user specifies.

查看更多
放我归山
5楼-- · 2019-04-18 01:52

There is the method set2DigitYearStart that can be used for that. It allows you to specify a start date. The parsed date will be in the interval [start date, start date + 100 years].

See the documentation for details.

查看更多
登录 后发表回答