javadate-differencejdatechooserdate

Calculating age from jDateChooser using ZoneId keeps returning 0


Im trying to calculate a users age based on their DOB input and compare it with todays date to work out their age in years. If they are under 12 they will be denied.

int YearDiff;
public void ageCalc()
{
    ZoneId nowBrit = ZoneId.of("Europe/London");
    LocalDate timeBrit = LocalDate.now(nowBrit);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
    int YearNow = Integer.parseInt(sdf.format(timeBrit));
    int YearSel = Integer.parseInt(sdf.format(jDateChooserDOB.getDate()));
    YearDiff = YearNow - YearSel;
}

The YearDiff variable will then be tested to see if its less than 12 in an if statement however it always returns 0.

Also if there is a better way to do age verification please do share.

Thanks in advance


Solution

  • The old-fashioned SimpleDateFormat class cannot format any of the modern objects of the java.time classes like LocalDate. Therefore the following line throws an exception:

        int YearNow = Integer.parseInt(sdf.format(timeBrit));
    

    The exception is java.lang.IllegalArgumentException: Cannot format given Object as a Date. This causes the remainder of your method not to be executed. And therefore you are never assigning any value to YearDiff. It being a field it has a default value of 0, which is therefore the result you see.

    Apparently you didn’t see the exception? If this is so, you’ve got a more serious problem than an incorrect result, either in your code (an empty catch block, known as “swallowing exceptions”?) or you project setup. Please fix first thing.

    Where I come from people get one year older on their birthday, not at New Year (when the year changes). I know it is not so everywhere in the world. In any case please search the Internet for the correct way of calculating an age according to your culture. Only skip the pages using the old and outdated classes like Date, Calendar, GregorianCalendar, DateFormat and SimpleDateFormat. java.time is so much nicer to work with and has better support for age calculation.

    PS Since jDateChooserDOB.getDate() returns an old-fashioned Date, convert it to Instant and perform further conversions from there, for example:

        int yearSel = jDateChooserDOB.getDate().toInstant().atZone(nowBrit).getYear();