I must calculate my age in years, months, days, hours, minutes and seconds. I have only been able to calculate years, months and days. How could I calculate in hours, minutes and seconds?
package age;
import java.time.LocalDate;
import java.time.Period;
import java.util.Scanner;
public class Age {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your birthdate:");
System.out.println("Year: ");
int year = sc.nextInt();
System.out.println("Month: ");
int month = sc.nextInt();
System.out.println("Day: ");
int day = sc.nextInt();
LocalDate today = LocalDate.now();
LocalDate birthdate = LocalDate.of(year, month, day);
Period p = Period.between(birthdate, today);
System.out.println("I am " + p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days old.");
}
}
Use the library
In my opinion it is more compact using GregorianCalendar and Date :
Of course, admitting the error raised by Elenasys in the calculation for the months.
From your proposed code, it is a bit complicated to have an exact calculation, due to the fact that you have to check which months are included in the calculation and, as you know, the months can have different numbers of days.
If we take the average number of days that a month can have
30.4167
in a year, the result can be obtained (considering a small margin of error in the calculation).