Friday, August 9, 2013

Calculate days lived since birth date

Just a small piece of code showing how to calculate total days lived since birth date (to current date):
import java.util.Calendar;
import java.util.GregorianCalendar;
 
public class TotalLifeTimeDays {
  
 public int getLifeTimeDays(int birthYear, int birthMonth, int birthDay) {
   
  Calendar birthDayCal = new GregorianCalendar();
     Calendar currentDayCal = Calendar.getInstance();
 
  birthDayCal.set(birthYear, birthMonth, birthDay);    
  return (int)((currentDayCal.getTime().getTime() - birthDayCal.getTime().getTime())
     / (1000 * 60 * 60 * 24));  
 }
  
 public static void main(String[] args) {
  TotalLifeTimeDays totalLifeTimeDays = new TotalLifeTimeDays();
  int totalDays = totalLifeTimeDays.getLifeTimeDays(1982, 11, 20);
  System.out.println("Total days lived: " + totalDays);
 }
}

No comments:

Post a Comment