Created
February 17, 2017 00:20
-
-
Save javerosanonimos/3640161f18f8527bcf5088414f10bc91 to your computer and use it in GitHub Desktop.
Código para calcular la edad a partir de una fecha de nacimiento
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.SimpleDateFormat; | |
import java.util.Calendar; | |
import java.util.Date; | |
/** | |
@Autor: www.javerosanonimos.com | |
Twitter: @javerosanonimos | |
Facebook: www.facebook.com/JaverosAnonimos | |
e-mail: javerosanonimos@gmail.com | |
**/ | |
class CalculaFecha { | |
public static void main(String []args){ | |
//Accedemos al metodo estatico a través del nombre de nuestra clase | |
System.out.println(CalculaFecha.calcularEdad("01-01-1999")); | |
/**Podemos quitar el static al metodo y se accedería así: | |
CalculaFecha cal= new CalculaFecha(); | |
cal.calcularEdad("01-01-1999");*/ | |
} | |
//Este es el método calcularEdad que se manda a llamar en el main | |
public static Integer calcularEdad(String fecha){ | |
Date fechaNac=null; | |
try { | |
/**Se puede cambiar la mascara por el formato de la fecha | |
que se quiera recibir, por ejemplo año mes día "yyyy-MM-dd" | |
en este caso es día mes año*/ | |
fechaNac = new SimpleDateFormat("dd-MM-yyyy").parse(fecha); | |
} catch (Exception ex) { | |
System.out.println("Error:"+ex); | |
} | |
Calendar fechaNacimiento = Calendar.getInstance(); | |
//Se crea un objeto con la fecha actual | |
Calendar fechaActual = Calendar.getInstance(); | |
//Se asigna la fecha recibida a la fecha de nacimiento. | |
fechaNacimiento.setTime(fechaNac); | |
//Se restan la fecha actual y la fecha de nacimiento | |
int año = fechaActual.get(Calendar.YEAR)- fechaNacimiento.get(Calendar.YEAR); | |
int mes =fechaActual.get(Calendar.MONTH)- fechaNacimiento.get(Calendar.MONTH); | |
int dia = fechaActual.get(Calendar.DATE)- fechaNacimiento.get(Calendar.DATE); | |
//Se ajusta el año dependiendo el mes y el día | |
if(mes<0 || (mes==0 && dia<0)){ | |
año--; | |
} | |
//Regresa la edad en base a la fecha de nacimiento | |
return año; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment