简体   繁体   中英

Calculate current Age ; using Java

I am trying to calculate the current age of a user .. but using the format i would like to use has caused some issues for me .

I could just ask separately for the year , month and day but much rather prefer (mm/dd/yyyy)

//Need help turning (mm/dd/yyyy) that the user inputs into:

//yyyy;

//mm;

// dd;


package org.joda.time;

import java.util.Calendar;
import java.util.GregorianCalendar;//needed for leap year
import java.util.Scanner;
import java.io.*;

public class AgeCalculation{
  public static void main(String[] args) throws IOException{




  int day = 1, month = 0, year = 1, ageYears, ageMonths, ageDays;
  Scanner myScanner = new Scanner(System.in);

  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  Calendar cd = Calendar.getInstance();
  try{


  System.out.print("Enter your Date of Birth.(mm/dd/yyyy): "); 
  Dob = myScanner.nextLine() ;

  // how to get year , month and date from (mm/dd/yyyy) format?


  year = ;
  if(year > cd.get(Calendar.YEAR)){
  System.out.print("Invalid date of birth.");
  System.exit(0);
  }
  month = 
  if(month < 1 || month > 12){
  System.out.print("Please enter monthe between 1 to 12.");
  System.exit(0);
  }
  else{
  month--;
  if(year == cd.get(Calendar.YEAR)){
  if(month > cd.get(Calendar.MONTH)){
  System.out.print("Invalid month!");
  System.exit(0);
  }
  }
  }
  if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 || 
  month == 9 || month == 11){
  if(day > 31 || day < 1){

      //leap year data below 

  System.out.print("Please enter day between 1 to 31.");
  System.exit(0);
  }
  }
  else if(month == 3 || month == 5 || month == 8 || month == 10){
  if(day > 30 || day < 1){
  System.out.print("Please enter day between 1 to 30.");
  System.exit(0);
  }
  }
  else{
  if(new GregorianCalendar().isLeapYear(year)){
  if(day < 1 || day > 29){
  System.out.print("Please enter day between 1 to 29.");
  System.exit(0);
  }
  }
  else if(day < 1 || day > 28){
  System.out.print("Please enter day between 1 to 28.");
  System.exit(0);
  }
  }
  if(year == cd.get(Calendar.YEAR)){
  if(month == cd.get(Calendar.MONTH)){
  if(day > cd.get(Calendar.DAY_OF_MONTH)){
  System.out.print("Invalid date!");
  System.exit(0);
  }
  }
  }
  }
  catch(NumberFormatException ne){
  System.out.print(ne.getMessage() + " is not a legal entry!");
  System.out.print("Please enter number.");
  System.exit(0);
  }
  Calendar bd = new GregorianCalendar(year, month, day);
  ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
  if(cd.before(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
  ageYears--;
  ageMonths = (12 - (bd.get(Calendar.MONTH) + 1)) + (bd.get(Calendar.MONTH));
  if(day > cd.get(Calendar.DAY_OF_MONTH)){
  ageDays = day - cd.get(Calendar.DAY_OF_MONTH);
  }
  else if(day < cd.get(Calendar.DAY_OF_MONTH)){
  ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
  }
  else{
  ageDays = 0;
  }
  }
  else if(cd.after(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
  ageMonths = (cd.get(Calendar.MONTH) - (bd.get(Calendar.MONTH)));
  if(day > cd.get(Calendar.DAY_OF_MONTH))
  ageDays = day - cd.get(Calendar.DAY_OF_MONTH) - day;
  else if(day < cd.get(Calendar.DAY_OF_MONTH)){
  ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
  }
  else
  ageDays = 0;
  }
  else{
  ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
  ageMonths = 0;
  ageDays = 0;
  }
  System.out.print("Age of the person : " + ageYears + " year, " + ageMonths + 
  " months and " + ageDays + " days.");
  }
}

Here's a hint as how you could read in and parse the entered date:

SimpleDateFormat f = new SimpleDateFormat("MM/dd/yyyy"); //note that mm is minutes, so you need MM here
Scanner s = new Scanner( System.in );

String dateLine = s.nextLine();
try
{
  Date d = f.parse( dateLine );
  System.out.println(d);
}
catch( ParseException e )
{
  System.out.println("please enter a valid date in format mm/dd/yyyy");
}

That's just an example and should get you started with reading the date correctly.

For getting the years, days and months in between two dates I'd still recommend using JodaTime since that makes life much easier.

Using standard Java facilities, this could help you:

Calendar c = Calendar.getInstance();
c.setTimeInMillis( System.currentTimeMillis() - d.getTime() );
System.out.println( c.get( Calendar.YEAR ) - 1970 ); //since year is based on 1970, subtract that
System.out.println( c.get( Calendar.MONTH ) );
System.out.println( c.get( Calendar.DAY_OF_MONTH ) );

Note that you need to subtract the smaller date from the bigger, ie the difference must be positive (which should be true when subtracting birth dates from the current time).

This would give a difference of 0 years, 9 full months and 26 days between Jan 1st 2011 and Oct 26th 2011, and a difference of 21 years and 1 day (since we already started this day) between Oct 26th 1990 and Oct 26th 2011.

If you want to use JodaTime:

String dob = myScanner.nextLine();
DateTimeFormatter format = DateTimeFormatter.forPattern("MM/dd/yyyy");
DateTime dateTimeOfBirth = DateTime.parse(dob, format);

year = dateTimeOfBirth.getYear();
// Etc

try this, it out puts the age into a form field called age in a form called "form", assumes you called your textbox(where DOB is entered) "dob"

var d =document.getElementById('dob').value.split('/'); 
var today = new Date(); 
var bday = new Date(d[2],d[1],d[0]);
var age = today.getFullYear() - bday.getFullYear();  
if(today.getMonth() < bday.getMonth() || (today.getMonth() == bday.getMonth() && today.getDate() < bday.getDate()))  
{
     t = age--;  
}
else {
t = age
}
form.age.value = t; 
} 

You'll pobably need something like that:

SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy", Locale.US);
Date date = sdf.parse(timestamp);
Calendar cd = Calendar.getInstance();
cd.setTime(date);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM