Home‎ > ‎Applied Core Java‎ > ‎Introduction‎ > ‎

Date Arithmetic

 

Problem :

Calculate your  age if Date of Birth is given?

Program :

Step 1 - Coding

Create a text file c:\sunilos\DateArithmetics.java  and copy below contents.

import java.util.*;

/*
 * A program that displays Calendar important methods
*/
public class DateArithmetics {

public static void main(String[] args) {

        // Date of birth
        int year = 2009;
        int month = 1; // Month index starts with 0, 0-Jan, 1-Feb, .. 11- Dec
        int day = 2;

        Calendar cDob = new GregorianCalendar(year, month, day);

        // date of birth is
        Date dob = new Date(cDob.getTimeInMillis());
        System.out.println("Your Date Of Birth is " + dob.toString());

        // How old you are?
        Calendar cd = Calendar.getInstance(); // get current date

        // If dob id greater than cd than you are still not born
        if (cd.before(cDob)) {            // Compare date
            System.out.println("You will take birth in future on "
                    + dob.toString());
        }

        // if cd is dob is less than current date then calculate Age
        if (cd.after(cDob)) { // Compare date
            int diffYear = cd.get(Calendar.YEAR) - cDob.get(Calendar.YEAR);
            int diffMonth = cd.get(Calendar.MONTH) - cDob.get(Calendar.MONTH);
            int diffDay = cd.get(Calendar.DAY_OF_MONTH)
                    - cDob.get(Calendar.DAY_OF_MONTH);

            //Calculate Age
            double age = diffYear + (diffMonth/12.00) + diffDay/(30 * 12.00); 

            System.out.println("Your Age is " + age + "years");

        }

    }

}


Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copyDateArithmetics.java into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. CompileDateArithmetics.java with help of 
    • javac DateArithmetics.java command. Command will create class file in the same folder.
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of
    • java DateArithmetics command.

Output

Your Date Of Birth is Mon Feb 02 00:00:00 IST 2009
Your Age is 0.6055555555555556years


<<Previous | Next>>
ċ
DateArithmetics.java
(1k)
Mahima Hardia,
Aug 20, 2011, 6:01 AM
Comments