Skip to content

Instantly share code, notes, and snippets.

@LucioD3v
Created February 25, 2025 22:17
Show Gist options
  • Save LucioD3v/76b0187053c4786d63615392eccc495a to your computer and use it in GitHub Desktop.
Save LucioD3v/76b0187053c4786d63615392eccc495a to your computer and use it in GitHub Desktop.
This Java application calculates the age of a user based on their birthdate. It also provides additional information such as the number of days until the user's next birthday and wishes them a happy birthday if today is their birthday.
import java.time.LocalDate;
import java.time.Period;
import java.util.Scanner;
public class AgeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter their birth year
System.out.println("Enter your birth year: ");
int year = scanner.nextInt();
System.out.println("Enter your birth month: ");
int month = scanner.nextInt();
System.out.println("Enter your birth day: ");
int day = scanner.nextInt();
LocalDate birthDate = LocalDate.of(year, month, day);
LocalDate currentDate = LocalDate.now();
if (birthDate.isAfter(currentDate)) {
System.out.println("Birthdate cannot be in the future.");
} else {
Period age = Period.between(birthDate, currentDate);
System.out.println("You are " + age.getYears() + " years, " + age.getMonths() + " months, and " + age.getDays() + " days old.");
if (birthDate.getMonth() == currentDate.getMonth() && birthDate.getDayOfMonth() == currentDate.getDayOfMonth()) {
System.out.println("Happy Birthday!");
} else {
LocalDate nextBirthday = birthDate.withYear(currentDate.getYear());
if (nextBirthday.isBefore(currentDate) || nextBirthday.isEqual(currentDate)) {
nextBirthday = nextBirthday.plusYears(1);
}
long daysUntilNextBirthday = java.time.temporal.ChronoUnit.DAYS.between(currentDate, nextBirthday);
System.out.println("Your next birthday is in " + daysUntilNextBirthday + " days.");
}
}
scanner.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment