void age() {
		boolean isValid = false;
		Calendar user = null;
		while (!isValid) {
			System.out.print("Enter Date (mm/dd/yyyy): ");
			DateFormat df = new SimpleDateFormat("MM/dd/yy");
			String s = In.in();
			Date date = null;
			try {
				date = df.parse(s);
			} catch (ParseException e) {
				System.out.println("Date error");
			}
			user = Calendar.getInstance();
			user.setTime(date);

			if (user.getTime().getTime() < calendar.getTime().getTime())
				isValid = true;
			else
				System.out.println("Invalid date. Enter again");
		}
		int userMonths = user.get(Calendar.MONTH);
		int userDays = user.get(Calendar.DATE);

		int day = calendar.get(Calendar.DATE);
		int month = calendar.get(Calendar.MONTH) + 1;
		hours = calendar.get(Calendar.HOUR_OF_DAY);
		minutes = calendar.get(Calendar.MINUTE);
		seconds = calendar.get(Calendar.SECOND);

		Date startDate = calendar.getTime();
		Date endDate = user.getTime();
		long l1 = startDate.getTime();
		long l2 = endDate.getTime();
		double d = (l1 - l2) * 0.001;

		int[] daysInMonths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
				31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

		double yearz = (d / 31536000);
		double monthz = ((yearz % 1) * 365) / 30.3167;

		int totalMonths = (int) monthz;
		int startingMonth = month;
		int totalDays = 0;

		if (userMonths < startingMonth) {

			if (userDays != day) {
				for (int i = userMonths + 1; i < startingMonth + 1; i++) {
					totalDays += daysInMonths[i - 1];
				}
			}
		} else if (userMonths >= startingMonth) {
			for (int i = 0; i <= ((12 - (userMonths + 1)) + month); i++) {
				totalDays += daysInMonths[i + userMonths];
			}
		}
		double daysToDivideBy = totalDays / (totalMonths + 1);
		double dayz = ((monthz % 1) * daysToDivideBy);

		System.out.println("You are: \nYears: " + (int) yearz + "\nMonths: "
				+ totalMonths + "\nDays: " + (int) dayz + "\nHours: " + hours
				+ "\nMinutes: " + minutes + "\nSeconds: " + seconds + " old");
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis((long) d);
		DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
		System.out.println(formatter.format(calendar.getTime()));
	}

This is what i have so far. It calculates the year and month correctly but it has a little trouble with the day
Ex.
if the user enters Dec. 1, 1990 for their birth date the output should be
You are 19 years, 4 months, 12 days, 8 hours, 44 minutes, and 39 seconds old.

Thanks in advance

Recommended Answers

All 2 Replies

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.