Age Calculator

Problem

Two dates are given on two lines: the birth date and today's date (YYYY-MM-DD, today is not before the birth date). Print the age in completed years. Someone born on 29 February is one year older on 1 March in a non-leap year.

Constraints

  • Years 1900 to 2100

Examples

Input

2000-05-15
2026-05-14

Output

25

Solutions

Best approachTime O(1)Space O(1)

The age is the difference of the years, but one year less if this year's birthday has not happened yet. Java's Period does the same. For 29 February, Java and this rule agree: the birthday counts from 1 March in a non-leap year.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Compute an age.
 * Input   : Birth date and today.
 * Output  : The completed years.
 * Approach: Compare month and day.
 * Time    : O(1)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int solve(String a, String b) {
        // Step 1: Period.between gives the years, months and days between two dates. The year part is the completed years.
        java.time.LocalDate birth = java.time.LocalDate.parse(a);
        java.time.LocalDate today = java.time.LocalDate.parse(b);
        return java.time.Period.between(birth, today).getYears();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String a = scanner.next();
        String b = scanner.next();
        System.out.println(solve(a, b));
    }
}
Hints (1)
  1. When do you subtract 1 from the year difference?