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

Answers


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.


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.


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.


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

Need Your Help

How set ListView not clickable

android android-listview clickable android-selector

I have this ListView that just needs to show data.

In python how to get name of a class inside its static method

python

how to get name of a class inside static method, i have inheritance