Ejemplo 1: java age from date
LocalDate today =LocalDate.now();LocalDate birthday =LocalDate.of(1987,09,24);Period period =Period.between(birthday, today);//Now access the values as belowSystem.out.println(period.getDays());System.out.println(period.getMonths());System.out.println(period.getYears());
Ejemplo 2: como calcular la edad a partir de la fecha de nacimiento en java usando el calendario
packagecom.candidjava.time;importjava.text.ParseException;importjava.text.SimpleDateFormat;importjava.time.LocalDate;importjava.time.Period;importjava.util.Calendar;importjava.util.Date;publicclassDobConversionpublicstaticvoidmain(String[] args)throwsParseException//direct age calculation LocalDate l =LocalDate.of(1998,04,23);//specify year, month, date directlyLocalDate now =LocalDate.now();//gets localDatePeriod diff =Period.between(l, now);//difference between the dates is calculatedSystem.out.println(diff.getYears()+"years"+ diff.getMonths()+"months"+ diff.getDays()+"days");//using Calendar ObjectString s ="1994/06/23";SimpleDateFormat sdf =newSimpleDateFormat("yyyy/MM/dd");Date d = sdf.parse(s);Calendar c =Calendar.getInstance();
c.setTime(d);int year = c.get(Calendar.YEAR);int month = c.get(Calendar.MONTH)+1;int date = c.get(Calendar.DATE);LocalDate l1 =LocalDate.of(year, month, date);LocalDate now1 =LocalDate.now();Period diff1 =Period.between(l1, now1);System.out.println("age:"+ diff1.getYears()+"years");
Comentarios y valoraciones
Agradecemos que quieras añadir valor a nuestro contenido informacional cooperando tu veteranía en las interpretaciones.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)