Java LocalDate Calculate getAge(LocalDate birthday)

Here you can find the source of getAge(LocalDate birthday)

Description

get Age

License

Apache License

Declaration

public static int getAge(LocalDate birthday) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Main {

    public static int getAge(LocalDate birthday) {
        LocalDate now = LocalDate.now();

        int age = now.getYear() - birthday.getYear();
        if (age <= 0) {
            return 0;
        }/* w w w  . j a  v a2 s.  co m*/

        int currentMonth = now.getMonthValue();
        int currentDay = now.getDayOfMonth();
        int bornMonth = birthday.getMonthValue();
        int bornDay = birthday.getDayOfMonth();
        if (currentMonth < bornMonth || (currentMonth == bornMonth && currentDay <= bornDay)) {
            age--;
        }

        return age < 0 ? 0 : age;
    }

    public static int getAge(Date birthday) {
        LocalDate birthdayDate = birthday.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        return getAge(birthdayDate);
    }

    public static int getAge(String birthday, String format) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        LocalDate birthdayDate = LocalDate.parse(birthday, formatter);
        return getAge(birthdayDate);
    }
}

Related

  1. dateToSystemLocalDate(Date d)
  2. daysAgo(LocalDate pastDate)
  3. doy(LocalDate date)
  4. fastDateWrite(LocalDate localDate)
  5. fastDateWriteWeeks(LocalDate localDate)
  6. getAge(LocalDate birthDay)
  7. getDate(ChronoLocalDate date)
  8. getDate(Console console, Function validator)
  9. getDate(final LocalDate localDate)