Program
import java.time.LocalDate; import java.time.Period; import java.util.Scanner; public class Age { public static void main(String[] args) { // TODO Auto-generated method stub System.out.print("Please enter date of birth in YYYY-MM-DD: "); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); scanner.close(); LocalDate dob = LocalDate.parse(input); System.out.println("Age is:" + getAge(dob)); } public static int getAge(LocalDate dob) { LocalDate curDate = LocalDate.now(); return Period.between(dob, curDate).getYears(); } }
Output
Please enter date of birth in YYYY-MM-DD: 1994-10-05 Age is:26
Description
public static LocalDate parse(CharSequence text, DateTimeFormatter formatter)
Obtains an instance of LocalDate from a text string using a specific formatter.
The text is parsed using the formatter, returning a date.
Parameters:
text – the text to parse, not null
formatter – the formatter to use, not null
Returns:
the parsed local date, not null
Throws:
DateTimeParseException – if the text cannot be parsed
public static LocalDate now()
Obtains the current date from the system clock in the default time-zone.
This will query the system clock in the default time-zone to obtain the current date.
Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.
Returns:
the current date using the system clock and default time-zone, not null
public int getYear()
Gets the year field.
This method returns the primitive int value for the year.
The year returned by this method is proleptic as per get(YEAR). To obtain the year-of-era, use get(YEAR_OF_ERA).
Returns:
the year, from MIN_YEAR to MAX_YEAR
public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
Obtains a Period consisting of the number of years, months, and days between two dates.
The start date is included, but the end date is not. The period is calculated by removing complete months, then calculating the remaining number of days, adjusting to ensure that both have the same sign. The number of months is then split into years and months based on a 12 month year. A month is considered if the end day-of-month is greater than or equal to the start day-of-month. For example, from 2010-01-15 to 2011-03-18 is one year, two months and three days.
The result of this method can be a negative period if the end is before the start. The negative sign will be the same in each of year, month and day.
Parameters:
startDateInclusive – the start date, inclusive, not null
endDateExclusive – the end date, exclusive, not null
Returns:
the period between this date and the end date, not null
See Also:
ChronoLocalDate.until(ChronoLocalDate)