Skip to main content
gamedev.net
🔒 Locked

[java] Caculating Age problem

Started by Halsafar 0 replies 300+ views
Original Post
Halsafar
Halsafar
Cant say this belongs in the Java section, buts is JAVA so here we go. I am not getting the appropriate results. They are out by a few days give or take... I was hoping someone may point out my flaw.

	private static void calculateAge() {
		Calendar cal = new GregorianCalendar();
		double dCurrentTime = cal.getTimeInMillis();
		System.out.println("Current time in ms: " + dCurrentTime);
		
		cal.set(m_iYear, m_iMonth - 1, m_iDay);
		double dTimeAtBirth = cal.getTimeInMillis();
		System.out.println("Time at birth in ms: " + dTimeAtBirth);	
			
		double dTimeDelta = dCurrentTime - dTimeAtBirth;
		double dSeconds = dTimeDelta / 1000.0;
		double dMinutes = dSeconds / 60.0;
		double dHours = dMinutes / 60.0f;
		double dDays = dHours / 24.0;
		double dMonths = dDays / 30.44;
		double dYears = dDays / 365.25;
		
		int iDays = (int)(dDays % 30.44); 
		int iMonths = (int)(dMonths % 12.0);
		int iYears = (int)(dYears);
		
		System.out.println("Age in days: " + dDays);
		System.out.println("Age in months: " + dMonths);
		System.out.println("Age in years: " + dYears);
		
		System.out.println(m_strName + " you are " + iDays + " days " + iMonths + " months " + iYears + " years old.");	
		System.out.println("Enter anything to continue -- Enjoy the input first though :) ");		
 		m_in.next();
	}

H_o_p_s
H_o_p_s
Using the calendar might be easier:
import java.util.*;public class code2{	public static void main(String[] args)	{		Calendar oldCal = Calendar.getInstance();		oldCal.set(2003,04,06); 		Calendar newCal = Calendar.getInstance();		newCal.set(2003,07,17); 		long oldMillis = oldCal.getTime().getTime();		long newMillis = newCal.getTime().getTime(); 		long diffInDays = (oldMillis - newMillis)/1000/60/60/24;		System.out.println("this is how many days: " + diffInDays); 	}}
BRING BACK THE BLACK (or at least something darker)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.