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):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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