簡體   English   中英

Java OOP - 如何獲得 DOB 中的年份和當前年份然后計算年齡?

[英]Java OOP - How to get year in DOB and current year then calculate age?

我有三個班級。 我的驅動程序類,人員類和家務類

我在兩個單獨的 csv 文件中列出了家務和家庭成員。

家庭成員文件只包含姓名和出生日期 (01/01/1901)。 所以我想做的第一件事是根據每個家庭成員的年齡計算他們的年齡並獲得當前年份然后獲得兩者的差異。 我如何選擇每個人的 dob 中的年份以及如何獲得當前年份?

   public int currentAge(LocalDate dob, LocalDate currentDate){
            if ((dob != null) && (currentDate != null)) {
                return Period.between(dob, currentDate).getYears();
            } else {
                return 0;
            }
        }
        public int getCurrentAge(){
            return currentAge;
        }

要從出生日期計算一個人的年齡,請使用 Java 8+ Time API,使用以下方法:

public static int getAge(LocalDate dob) {
    LocalDate today = LocalDate.now();
    int age = today.getYear() - dob.getYear();
    if (MonthDay.from(today).isBefore(MonthDay.from(dob)))
        age--; // before birthday in current year
    return age;
}

Java 8 兼容解決方案:

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

public class Demo
{
    public static void main(String[] args)
    {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");
        String date = "16/08/2016";
        LocalDate dob = LocalDate.parse(date, formatter);
        System.out.println(daysBetween(dob));
    }

    private static long daysBetween(LocalDate dob)
    {
        return Period
            .between(dob,
                LocalDate.now())
            .getYears();

    }
}

我們可以在People添加一個數據成員來保存雜務信息。

class People{
    private final String name;
    private final LocalDate dob;
    private final String gender;
    private List<Chores> choresList;
    }

您可以使用以下方法或類似的方法來獲取年齡:

private long daysBetween(Date one, Date two) {
    long difference =  (one.getTime()-two.getTime())/86400000;
    return Math.abs(difference);
}

在此處此處閱讀更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM