I need to check that a date entered in a form is valid.
I have the date separated into year, day and month. And I'm not interested in checking dates before 1900.
I am doing it with this code:
public class Fecha
{
int año;
int mes; // 1 a 12
int dia; // 1 a 31
}
static int[] diasMes= {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/**
* Comprueba si la fecha es correcta. Se comprueban solo fechas de 1900
* o posteriores.
* @param fecha La fecha a comprobar.
* @return true si la fecha es correcta, false en otro caso.
* @throws IllegalArgumentException si el año es menor que 1900.
*/
boolean validaFecha( Fecha fecha)
{
if ( fecha.año < 1900 ) {
throw new IllegalArgumentException(
"Solo se comprueban fechas del año 1900 o posterior");
}
if ( fecha.mes<1 || fecha.mes>12 )
return false;
// Para febrero y bisiesto el limite es 29
if ( fecha.mes==2 && fecha.año%4==0 )
return fecha.dia>=1 && fecha.dia<=29;
return fecha.dia>=0 && fecha.dia<=diasMes[fecha.mes-1];
}
The class Fecha
I use is somewhat more complicated, it has its setter, getter and other things, but those details are irrelevant to this question. The question is about the method validaFecha
.
Is the implementation correct? Is there a way to do it with the standard libraries?
Depending on the version of Java you are using, you have access to some classes that are already included in the JDK without requiring an external library (additional JAR files).
Since Java 8
If you're using Java 8, you can use class 1 to construct a date with the year, month, and day. Namely:
java.time.LocalDate
If any of the values (year, month, day) are invalid, the method
LocalDate.of
will throwjava.time.DateTimeException
.From JDK1.1
java.util.Date
If you are using Java 6/7, you can use the and 2 classes to construct a date with the year, month, and day. Namely:java.util.Calendar
It must be specified
calendar.setLenient(false);
to only allow values within the corresponding ranges (year, month, day). If any of these values are invalid, itCalendar
will throwjava.lang.IllegalArgumentException
.────────────
1. You can see some examples of this and other classes in Java SE 8 Date and Time .
2. You can see some examples in Java Date and Calendar examples . Also in Java Calendar Class .
No. Based on your code, I would change this part:
Since the rule for leap years is (emphasis mine):
This means:
The easiest way to adapt this in your code is:
Another error you have is in this part:
Which is on the last line of the method. Should be
fecha.dia >=1
If you want to use the JDK classes, in addition to the options indicated by @PaulVargas, you can use
SimpleDateFormat
, available in any version of Java (since 1.5 that I remember). Here the code: