JAVA – How To Calculate An Age From A Date Of Birth (DOB)

The following code illustrates how to derive an age from a given DOB.

This example uses the DOB format YYYY-MM-DD.

This can be altered to any format by changing the substrings taken from the original DOB input.

String dob = “1984-09-20”;

//TAKE SUBSTRINGS OF THE DOB SO SPLIT OUT YEAR, MONTH AND DAY
//INTO SEPERATE VARIABLES
int yearDOB = Integer.parseInt(dob.substring(0, 4));
int monthDOB = Integer.parseInt(dob.substring(5, 7));
int dayDOB = Integer.parseInt(dob.substring(8, 10));

//CALCULATE THE CURRENT YEAR, MONTH AND DAY
//INTO SEPERATE VARIABLES
DateFormat dateFormat = new SimpleDateFormat(“yyyy”);
java.util.Date date = new java.util.Date();
int thisYear = Integer.parseInt(dateFormat.format(date));

dateFormat = new SimpleDateFormat(“MM”);
date = new java.util.Date();
int thisMonth = Integer.parseInt(dateFormat.format(date));

dateFormat = new SimpleDateFormat(“dd”);
date = new java.util.Date();
int thisDay = Integer.parseInt(dateFormat.format(date));

//CREATE AN AGE VARIABLE TO HOLD THE CALCULATED AGE
//TO START WILL – SET THE AGE EQUEL TO THE CURRENT YEAR MINUS THE YEAR
//OF THE DOB
int age = thisYear – yearDOB;

//IF THE CURRENT MONTH IS LESS THAN THE DOB MONTH
//THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
//BIRTHDAY YET THIS YEAR
if(thisMonth < monthDOB){
age = age – 1;
}

//IF THE MONTH IN THE DOB IS EQUEL TO THE CURRENT MONTH
//THEN CHECK THE DAY TO FIND OUT IF THEY HAVE HAD THEIR
//BIRTHDAY YET. IF THE CURRENT DAY IS LESS THAN THE DAY OF THE DOB
//THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
//BIRTHDAY YET THIS YEAR
if(thisMonth == monthDOB && thisDay < dayDOB){
age = age – 1;
}

//THE AGE VARIBALE WILL NOW CONTAIN THE CORRECT AGE
//DERIVED FROMTHE GIVEN DOB
System.out.println(age);



This process calculates the current year, month and date to work out if the DOB has already passed this year in order to accuratly establish the age.

Advertisements

Java – Random Number Generator / How To Generate A Random Number

This is a simple method for generating a random number between zero (0) and a given number.

The following code example with generate a random number between 0 and 49.

Although the value of maxNumber is set to 50, Java will start the count at 0.

If you want a number between 0 and 50, set the value of maxNymber to 51.

int maxNumber = 50;
int randomNumber = (int)Math.floor(Math.random() * maxNumber);


How Fast Is A USB Connection?


Data transfer speed table

USB 1.0: > 2 MPPS
USB 2.0 FULL SPEED: 12 MBPS
USB 2.0 HIGH SPEED: 180 MBPS
FIREWIRE-400: 400 MBPS
FIREWIRE-800: 800 MBPS
ENTERNET [10BASE-T]: 10 MBPS
FAST ETHERNET [100BASE-T]: 100 MBPS
GIGABIT ETHERNET [1000BASE-X]: 1000 MBPS
ATA-133: 1064 MBPS
SATA-150: 1200 MBPS





NOTE: these are rough speeds that may be possible.

The typical sustained transfer rate will be lower. Data rate is also dependent on the system architecture, the PCI bus and the attached USB devices