0

I'm practicing using encapsulation in java to create an Employees profile. I'm trying to include both the employees age - calculated using

private Period age;
private LocalDate currentDate;
private LocalDate dob;
public Period calcAge() {
    currentDate = LocalDate.now();
    age = Period.between(currentDate, dob); //dob is Date Of Birth
    return age;
}

, and the age at which they were hired. My first thoughts were to accomplish this with the following method:

public Period hiredAge() {
    return Period.between(age, hireDate);
}

However, I receive the error "Period cannot be converted to LocalDate"

I've tried to research both a way to perform the calculation using "age" as a LocalDate - and by inputting hireDate as a Period, both to no avail. How can I calculate the age at which the Employee was hired?

ddalcanto
  • 51
  • 5
  • 2
    *I'm practicing using encapsulation*: OK, but then start by understanding the difference between a field and a local variable. A field is part of the state of an object. It's normal for an employee to have a date f birth. But an employee shouldn't have a currentDate. That should be a local variable. And since the age can be computed from the date of birth, and since it keeps changing, it should be a local variable, too. – JB Nizet Nov 23 '18 at 00:18
  • 1
    nit: Do you really want to represent age as a `Period` instead of an `int` or `float`? – Krease Nov 23 '18 at 00:23
  • Why do you not simply use `ChronoUnit.YEARS.between(dob, currentDate)`? – Meno Hochschild Nov 23 '18 at 11:07

1 Answers1

0

Just like you calculated age using Period.between(currentDate, dob), you can calculate the age at which they were hired using Period.between(dob, hireDate).

BTW you are getting that error because you are passing age, which is a Period, not a LocalDate in Period.between(age, hireDate).

Kartik
  • 7,677
  • 4
  • 28
  • 50