2

I have tried to compare to Dates the Birthdate and the Current date and then I tried to get the age. But the Current date Funtion begins with another Date than the given date My Code:

GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
long ms = System.currentTimeMillis() - birthdate.getTimeInMillis();
double years = (((double)ms / 1000)/31536000) ;
System.out.print(years);
// years Shoud be 18 here but it returns 17.3
if (years > 18) {
  // Code Block
}
else{
  System.out.print("to Jung");
}
Klaus
  • 31
  • 3

3 Answers3

1

Check the Constructor on GregorianCalendar.

public GregorianCalendar(int year, int month, int dayOfMonth)

Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.

year - the value used to set the YEAR calendar field in the calendar.

month - the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January.

dayOfMonth - the value used to set the DAY_OF_MONTH calendar field in the calendar.

You are creating a July 20th date, which is coincidentally offset by a single month, or approximately 0.08 years.

Compass
  • 5,502
  • 4
  • 27
  • 40
  • Thanks so i must change the month to 05 and work with the correct number of Millisekunds in the Year 31.556.926.080ms‬ instead of 31.536.000.000ms – Klaus Jun 20 '19 at 16:46
1
LocalDate birthdate = LocalDate.of(2001,06,20);
LocalDate currentdate = LocalDate.now();
int years = Period.between(birthdate , currentdate).getYears();
if (years >= 18) {
  // Code
} else {
  System.out.print("Sie sind zu Jung");
}

It Worked like this but I must change the hole code because everything was written with the GeorgianCalender.

Klaus
  • 31
  • 3
0

I couldn't tell you why exactly your code, which should technically work, doesn't: there seems to be inaccuracies (leap days?) in the Calendar, or I'm missing something. Thanks to Compass, I know that I was missing something: months are 0-indexed in the constructor for Gregorian Calendar. 06 is July.

However, you shouldn't compare dates like this. If you don't want to use any other library, you can do this:

    GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
    GregorianCalendar today = new GregorianCalendar();
    birthdate.add(Calendar.YEAR, 18);
    System.out.print(birthdate.getTime().after(today.getTime()));
Docteur
  • 1,179
  • 16
  • 28