1

i'm trying to create a small command line java app that will allow the input of a date and compare it to the current date and return an integer that represents the number of years between the entered date and the current date. this is to calculate the age of a living person in years. So far, I've found that I need to use the Calendar object, but I can't figure out how to subtract the entered year from the current year and return an integer. Can you help? Just hit the high points on the mechanics of comparing the dates. Thanks.

1 Answers1

2

Once you have a Calendar object initialized with the correct date, you can call the get(Calendar.YEAR) value to get an integer representing the year. Do this for both dates and subtract.

You'll also want to get the month and date and compare, because if the end date has a lower month/date than the start, then you'll want to subtract 1 from the earlier result (the year has not yet been completed).

Typically for birthdays you don't care about the time component (hour/minute/second), so some libraries may give you a different result (in an extremely small number of cases) -- it's justifiable to roll your own for this case.

  • Thank you. I got it working. Now I have a new problem. I created a separate class that does all the age calculations. I have a main class that instantiates and does the work. But When I try to run it at the command line like this: java Age 1970 12 12 it throws a laundry list of exceptions complaining that it can't find the calculation class that is sitting in the directory right beside it. I haven't done enough work with deployment and the jar tool to know how to fi this. – Osgaldor Jason Storm Feb 17 '13 at 01:12
  • It works beautifully in Netbeans when I set up the runtime arguments in the project's Run properties. I built this to be a command line tool. What the devil am I doing wrong? – Osgaldor Jason Storm Feb 17 '13 at 01:14