 |
My first TWiki page, A Simple Age Calculator Class.
Sometimes you need to calculate an Age of the person knowing it's birthday.
It seems like a trivial task, but many beginners trying to reinvent the wheel while doing it.
Tip A simple search on java.sun.com forums gives you an idea what some developers doing
a simple search (will open in this window)
To show that age calculation should not be such a pain, I put together a small class that calculates your age based on given birthday.
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.text.SimpleDateFormat;
import java.text.ParseException;
/**
* User: IvanLatysh@yahoo.ca
* Date: 27-May-2004
* Time: 6:57:04 PM
*/
public class Age {
public Age(long birthday) {
Calendar age = Calendar.getInstance(Locale.getDefault());
age.setTimeInMillis(Math.abs(birthday-System.currentTimeMillis()));
System.out.println("Your are "+(age.get(Calendar.YEAR)-1970)+" years, "+age.get(Calendar.MONTH)+" month, "+age.get(Calendar.DAY_OF_MONTH)+" days "+(System.currentTimeMillis()-birthday<0 ?"Not Born Yet" :"Old")+".");
}
public static void main(String[] args) {
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
if (args.length==0) {
System.out.println("Usage:\n java Age dd/mm/yyyy\nWhere:\n dd - date\n mm - month\n yyyy - year");
} else {
try {
final Date birthday = dateFormatter.parse(args[0]);
System.out.println("Your birthday is " + dateFormatter.format(birthday));
final Age myAge = new Age(birthday.getTime());
} catch (ParseException e) {
System.out.println("Error parsing your birthday.");
e.printStackTrace();
}
}
}
}
How to use it:
- Copy the code from this page into the new file Age.java
- Compile it
C:\> javac Age.java
- Run it
C:\> java Age 10/10/2004
- Have fun.
-- Main.ivanlatysh - 28 May 2004
|