Calculate age in years, months, days, hours, minutes, and seconds

I need to accept the birthday entered by the user (preferably in the format dd/mm//yyyy ) and find their age based on today's date. Can someone explain to me the process that I have to go through to find this? I need to print it in the format:

"You are 19 years old, 4 months, 12 days, 8 hours, 44 minutes and 39 seconds."

I got a little confused about how to subtract the date from another date and how I will refer each part (years, months, days, hours, etc.) separately.

The code that I currently have for reference:

 import java.sql.Date; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Scanner; public class Driver { public Driver(){} public static void main( String[] args){ Driver menu = new Driver(); MenuOptions option; do{ menu.displayMenu(); option = menu.getResponse(); menu.runOption(option); }while(option != MenuOptions.Quit); } private enum MenuOptions{ AgeCalc("Calculate your age"), AnniversaryCalc("Calculate time until specified date"), AgeDifference("Find the time between two specified dates"), Quit("Exit the program"); private String value; private MenuOptions(String value){ this.value = value; } public String toString(){ return value; } } public void displayMenu(){ for(MenuOptions option : MenuOptions.values()){ System.out.printf("%5d: %s\n", option.ordinal()+1, option); } } public MenuOptions getResponse(){ int value = -1; Scanner input = new Scanner(System.in); do{ System.out.println("> "); String response = input.nextLine(); if(response.matches("\\d+")){ value = Integer.parseInt(response); if(value < 1 || value > MenuOptions.values().length){ value = -1; System.out.println("Unknown response, please enter a number between 1 and " +MenuOptions .values().length); } } }while(value <=0); return MenuOptions.values()[value-1]; } public void runOption(MenuOptions option){ Scanner in = new Scanner(System.in); switch(option){ case AgeCalc: System.out.println("Please enter your birthday mm/DD/yyyy)."); System.out.println(">"); DateFormat df = new SimpleDateFormat("mm/DD/yyyy"); try { java.util.Date birthday = df.parse(in.nextLine()); System.out.println("Today = " + df.format(birthday)); } catch (ParseException e) { e.printStackTrace(); } Calendar today = Calendar.getInstance(); java.util.Date today = df.format(); DateFormat simple = new SimpleDateFormat("dd/MM/yyyy"); String birthdate = simple.format(in.nextLine()); Date.parse(birthdate); System.out.println(birthdate.toString()); break; case AnniversaryCalc: System.out.printf("PI: %.20f\n", Math.PI); break; case AgeDifference: for(int p=0; p <= 32; p++){ System.out.println("2^" +p+" = " +Math.pow(2,p)); } } } } 
+3
source share
4 answers

I would suggest using Joda time . This is a much better API than what is included in the JDK.

Create an instant view representing when a person was born, another representing the current time, and use these two Instant to create a period . From there it is easy to get the required fields using the methods presented in the Period class.

+5
source

java.time

Using the java.time framework built into Java 8 and later. Example: copy using Tutorial (with slight modifications).

 import java.time.Period import java.time.LocalDate import java.time.format.DateTimeFormatter DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy"); LocalDate today = LocalDate.now(); LocalDate birthday = LocalDate.parse("1/1/1960", formatter); Period p = Period.between(birthday, today); System.out.println("You are " + p.getYears() + " years, " + p.getMonths() + " months and " + p.getDays() + " days old."); 

The code produces output similar to the following:

You are 53 years old, 4 months and 29 days old.

In my opinion, it makes no sense to display hour, minute and second, because you probably will not have such accurate data in your database. This is why the example uses LocalDate instead of LocalDate .

+3
source

There are several ways. I would use joda-time , using the Period class to represent the delta between today and the date of birth. It provides exactly what you want.

If you do not want to deal with a third-party library, you will get Date objects representing the two specified dates, and call getTime() on both, subtract the last from the earliest and you will have a delta between the dates in milliseconds. Mathematics to convert to years / months / days, etc. Trivial. * Sort of:

 delta /= 1000; // convert ms to s if (delta > 60 * 60 * 24 * 365) // number of seconds in a year int years = delta / (60 * 60 * 24 * 365) // integer division to get the number of years delta %= (60 * 60 * 24 * 365) // assign the remainder back to delta // repeat ad nauseum 
  • When I speak trivially, I mean, it would seem, simple, but full of complex details, for example, what is the definition of a month (30 days? 365/12 days?) And how do you deal with leap years and summer days and time zones. Personally, I will stick to iodine time.
+1
source

The best way I've found is to use two separate instances of the Calendar and subtract the values ​​YEAR, MONTH, DAY, etc. Between themselves:

  Calendar cal1 = Calendar.getInstance(); cal1.setTime(birthdate); Calendar cal2 = Calendar.getInstance(); cal2.setTime(new Date()); int years = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR); int months = cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH); int days = cal2.get(Calendar.DAY_OF_MONTH) - cal1.get(Calendar.DAY_OF_MONTH); int hours = cal2.get(Calendar.HOUR_OF_DAY) - cal1.get(Calendar.HOUR_OF_DAY); int minutes = cal2.get(Calendar.MINUTE) - cal1.get(Calendar.MINUTE); TextView ageTextView = findViewById(R.id.textview_age); ageTextView.setText("y: "+years+", m: " + months + ", d: "+days+ " ,h: "+hours+", min: "+minutes); 
0
source

All Articles