Taking into account the information that @Ajeno provides regarding the CURP another way to solve it would be through SimpleDateFormat # set2DigitYearStart (date )
set2DigitYearStart(startDate)
allows to indicate that the first 2 digits will be taken into account during the pairing of a date and if we format with the abbreviated format yy
will build the date from those two first digits.
The startDate
parameter determines a range of dates to consider :
startDate - During parsing, two digit years will be placed in the range startDate to startDate + 100 years.
That is, calling it with 1900
will take the period 1900-2000
and invoking it with 2000
will take 2000-2100
, in any case SimpleDateFormat
will locate the date with format yy/mm/dd
within that range.
Examples (pseudocodigo):
df.set2DigitYearStart(2000)
df.format(88/5/12) -> 2088/5/12
df.set2DigitYearStart(1970)
df.format(70/5/12) -> 2070/5/12
df.set2DigitYearStart(1970)
df.format(90/5/12) -> 1990/5/12
Note that in the latter case as the period is from 1970 - 2070 and does not exist in that period the year 2090 takes 1990
Demo
Solution to the problem that the OP raises :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
String fechaNacimiento= "03/05/27";
Calendar cal = Calendar.getInstance();
if(request.getCurp().substring(17,18).matches("[0-9]+")){
cal.set(Calendar.YEAR, 1900); // si es un digito corresponde a los 19XX
}else{
cal.set(Calendar.YEAR, 2000); // sino, corresponde a 20XX
}
dateFormat.set2DigitYearStart(cal.getTime()); // a partir de este punto dateFormat conoceque dos primeros digitos tomar al parsear
cal.setTime(dateFormat.parse(fechaNacimiento));
System.out.println(cal.getTime());
What happens if we do not explicitly state the century? In the documentation of SimpleDateFormat is mentioned:
For parsing with the abbreviated year pattern ("and" or "and" and "),
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 of 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 "11/1/12" would be
interpreted as Jan 11, 2012 while the string "04/05/64" would be
interpreted as May 4, 1964.
That is, SimpleDateFormat
will take into account the period (fecha creación - 80 años)
to (fecha creación + 20 años)
and depending on which century the date to be parsed will determine which first two digits to use.