1

This is what I did, but it did not take into account the leap years

public static int calculateAge(String yyyyMMddBirthDate){
    DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd");
    Date birthDateDate = fmt.parse(yyyyMMddBirthDate);
    Date nowDate=new Date();
    long differenceInMillis=nowDate.getTime()-birthDateDate.getTime();
    int days=(int)Math.abs(differenceInMillis/(1000*60*60*24));
    int ages=(int)days/365;
    System.out.println(days+" days");


    return ages;
}

I heard we have to use Joda time to calculate ages, but seem GWT does not support Joda time.

Can we just simply use simple code to calculate ages in GWT rather than using library?

Note: This is GWT question, not Java one. The GWT does not support java.text or Joda.

Tum
  • 3,614
  • 5
  • 38
  • 63
  • possible duplicate of [How do I calculate someone's age in Java?](http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java) –  Sep 30 '14 at 03:48
  • @Jarrod, it require Joda library & I dont have in my GWT and I dont like to use it. Why we need to close this question? it 's gwt not Java – Tum Sep 30 '14 at 03:52
  • 1
    @JarrodRoberson this question is not a duplicate of http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java – Ruchira Gayan Ranaweera Sep 30 '14 at 04:08

4 Answers4

1

This should work (even for GWT), at least for births that are after about 1582:

// currentDate and birthDate are in the format yyyyMMdd
final int age = (Integer.valueOf(currentDate) - Integer.valueOf(birthDate)) / 10000;
Andy King
  • 1,632
  • 2
  • 20
  • 29
1

You've already calculated the age in milliseconds, but you need to convert it to the highly arbitrary Western "years."

Best to use a library like JodaTime or Calendar that have these edge cases programmed in. Luckily people have ported it to GWT.

See: Date time library for gwt

Update: It really depends on what answer you want. Generally, comparing the current year to the birth year would get you the correct answer. So, if you want integer years lived so far:

Date dateBirth = ...;
Date dateNow = new Date();
int yearsOld = dateNow.getYear() - dateBirth.getYear();

To account for the fractional year, you'll need to test for leap days (if you want day precision) or leap seconds (if you want leap second precision). So, again, it depends what result you seek, which you've not said.

Regardless, this has nothing to do with GWT and everything to do with the basics of date/time math. either you'll have to bring it in via a library, or do it yourself. I'd suggest a library, since the calculations are elaborate. Just look inside the BaseCalendar that Java uses.

Community
  • 1
  • 1
Joseph Lust
  • 19,340
  • 7
  • 85
  • 83
  • too complicated library for a simple function, can you figure out a very very simple way? – Tum Sep 30 '14 at 14:00
  • getYears was deprecated but since we dont have Calendar in GWT so it ok, but int yearsOld = dateNow.getYear() - dateBirth.getYear(); only count the years it is not as accurate as miliseconds. Ex, today is 1Oct14, birthday is 11 Oct 1977 then it should show 36 but it turned to 37, (the correct is 36 years and 8 months – Tum Sep 30 '14 at 15:38
  • @Tum, the entire Date type has LONG been deprecated, and yet so many libs still use it. Welcome to the Java party. ;) Regardless, no one ever cares how old you are in MS in the real world, so adapt the code as needed to your use case. – Joseph Lust Sep 30 '14 at 20:06
0

I ran into this today and here's what I came up with. This models how I would mentally calculate someone's age given a date of birth. (using com.google.gwt.i18n.shared.DateTimeFormat)

private int getAge(Date birthDate) {
    int birthYear = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(birthDate));
    int birthMonth = Integer.parseInt(DateTimeFormat.getFormat("MM").format(birthDate));
    int birthDayOfMonth = Integer.parseInt(DateTimeFormat.getFormat("dd").format(birthDate));
    Date today = new Date();
    int todayYear = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(today));
    int todayMonth = Integer.parseInt(DateTimeFormat.getFormat("MM").format(today));
    int todayDayOfMonth = Integer.parseInt(DateTimeFormat.getFormat("dd").format(today));

    boolean hasHadBirthdayThisYear;
    if (todayMonth < birthMonth) {
        hasHadBirthdayThisYear = false;
    } else if (todayMonth > birthMonth) {
        hasHadBirthdayThisYear = true;
    } else {
        hasHadBirthdayThisYear = birthDayOfMonth <= todayDayOfMonth;
    }

    int age = todayYear - birthYear;
    if (!hasHadBirthdayThisYear) {
        age--;
    }
    return age;
}
akulzer
  • 11
  • 3
-2
import java.util.*;

public class Practice2 {
    public static int calculateAge(String yyyyMMddBirthDate) {
        // check the input ?            
        int birthYear = Integer.parseInt(yyyyMMddBirthDate.substring(0,4));
        Date nowDate = new Date();
        int nowYear = nowDate.getYear() + 1900;

        //rough age and check whether need -- below
        int roughAge = nowYear - birthYear;

        int birthMonth = Integer.parseInt(yyyyMMddBirthDate.substring(5,7));
        int birthDay = Integer.parseInt(yyyyMMddBirthDate.substring(8,10));

        //1970-01-01T 00:00:00
        long now = nowDate.getTime();
        long days = now / (3600l * 1000l * 24l);
        int daySum = 0;
        for( int i = 1970; i < nowYear; i ++  ){
            daySum = daySum + yearDays(i);
        }
        int[] monthDays = {31, 28 , 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        monthDays[1] = yearDays(nowYear)  - 337;
        for( int i = 0; i < birthMonth -1; i ++ ){
            daySum = daySum + monthDays[i];
        }
        daySum = daySum + birthDay;


        if(  daySum > days ){
            roughAge--;
        }

        return roughAge;
    }

    private static int yearDays(int year) {
        if( ( (year%100==0)&&(year%400==0) )
                ||((year%100!=0)&&(year%4==0))){
            return 366;
        }
        return 365;
    }

    public static void main(String[] args) {
        System.out.println(calculateAge("1990-12-30"));
    }
}
paco alcacer
  • 381
  • 2
  • 13