How can I calculate the age of a person in year, month, days?

前端 未结 11 1248
谎友^
谎友^ 2020-11-27 05:52

I want to calculate the age of a person given the date of birth and the current date in years, months and days relative to the current date.

For example:

<         


        
11条回答
  •  囚心锁ツ
    2020-11-27 06:36

    Since years, months and even days can have uneven lengths, you can't start by subtracting the two dates to get a simple duration. If you want the result to match up with how human beings treat dates, you instead have to work with real dates, using your language's built in functions that understand dates better than you ever will.

    How that algorithm is written depends on the language you use, because each language has a different set of functions. My own implementation in Java, using the awkward but technically correct GregorianCalendar:

    Term difference (Date from, Date to) {
        GregorianCalendar cal1 = new GregorianCalendar();
        cal1.setTimeInMillis(from.getTime());
    
        GregorianCalendar cal2 = new GregorianCalendar();
        cal2.setTimeInMillis(to.getTime());
    
        int years = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR);
        int months = cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
        int days = cal2.get(Calendar.DAY_OF_MONTH) - cal1.get(Calendar.DAY_OF_MONTH);
        if (days < 0) {
            months--;
            days += cal1.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        if (months < 0) {
            years--;
            months += 12;
        }
        return new Term(years, months, days);
    }
    

    This may not be perfect, but it delivers human-readable results. Term is a class of my own for storing human-style periods, since Java's date libraries don't have one.

    For future projects I plan to move to the much better Joda date/time library, which does have a Period class in it, and will probably have to rewrite this function.

提交回复
热议问题