Skip to content

Instantly share code, notes, and snippets.

@javerosanonimos
Created February 17, 2017 00:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javerosanonimos/3640161f18f8527bcf5088414f10bc91 to your computer and use it in GitHub Desktop.
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
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