+ 1

Java 8 getAge calc

JAVA 8 - I am trying to calculate age with a single line of code. Trying to turn the below code into a single line of code? public Int getAge() { LocalDate today = LocalDate.now(); YearMonth diff = YearMonth.between(birthdate, today); //int age = today.getYear() - birthdate.getYear(); return diff; }

29th Nov 2018, 7:53 PM
Sushi_Theif
Sushi_Theif - avatar
5 Antworten
+ 2
This is specifically what i was looking for. I figured it out. public int getAge() { return Period.between(birthdate, LocalDate.now()).getYears(); }
29th Nov 2018, 8:35 PM
Sushi_Theif
Sushi_Theif - avatar
+ 3
I question some things about the code you posted such as Int return type with a capital i and "birthdate" that came out of nowhere but putting all those aside, I have never worked before with LocalDate so I don't know if there's an easier way for this but this is what I came up with: public int getAge(int birthDate) { return Integer.parseInt(String.valueOf(LocalDate.now()).substring(0, 4)) - birthDate; } gets today's date (2018-11-29), converts it to String, takes first 4 characters (2018), parses it to int, and subtracts birthDate from it (which is a method parameter) as a result, the answer would be 20 for getAge(1998); I hope this is what you asked for
29th Nov 2018, 8:15 PM
Shadowa
Shadowa - avatar
+ 1
Welp. Told you that I didn't have any experience with LocalDate so I couldn't know the existence of Period class. My answer had a more primitive solution rip Seems like I was the one to get to learn :D
29th Nov 2018, 8:44 PM
Shadowa
Shadowa - avatar
0
Sorry here is what i have import java.time.*; public class Person { //instance variables private String firstName; private String lastName; private LocalDate birthdate; // constructor public Person(String firstName ,String lastName, LocalDate birthdate) { this.firstName = firstName; this.lastName = lastName; this.birthdate = birthdate; } public int getAge() { return Period.between(birthdate, LocalDate.now()).getYears(); } //override toString() public String toString() { return firstName + " " + lastName + " " + getAge(); } }//end class
29th Nov 2018, 8:34 PM
Sushi_Theif
Sushi_Theif - avatar
0
Thanks for the response!
29th Nov 2018, 8:36 PM
Sushi_Theif
Sushi_Theif - avatar