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

此生再无相见时 提交于 2019-12-06 16:47:43

问题


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

回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/24903259/how-to-control-simpledateformat-parse-to-19xx-or-20xx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!