Calculate Date of person in Years, Months, Days, Hours, Min, sec

I am unable to find a faily simple algorthm
Can some one tell me one.

I was using this code but it seems to give wrong number of days

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")+".");

LVL 18
armoghanAsked:
Who is Participating?
 
zzynxConnect With a Mentor Software engineerCommented:
Looks like that last one is OK.

If you want it *without* deprecated functions (recommended):

          Calendar cal = Calendar.getInstance();
          cal.set(2004, 1, 10, 8, 12, 0); // the birthday remember the month start from 0
          int years = 0;
          int months = 0;
          int days = 0;
          int hours = 0;
          int mins = 0;
          int secs = 0;
          Calendar now = Calendar.getInstance();
          System.out.println("Now it's " +
               new SimpleDateFormat("dd MMMM yyyy hh:mm:ss").format(now.getTime()) );
          System.out.println("Since you're born on " +
               new SimpleDateFormat("dd MMMM yyyy hh:mm:ss").format(cal.getTime()));
          while (cal.get(Calendar.SECOND) != now.get(Calendar.SECOND)) {
               secs++;
               cal.add(Calendar.SECOND, 1);
          }
          while (cal.get(Calendar.MINUTE) != now.get(Calendar.MINUTE)) {
               mins++;
               cal.add(Calendar.MINUTE, 1);
          }
          while (cal.get(Calendar.HOUR_OF_DAY) != now.get(Calendar.HOUR_OF_DAY)) {
               hours++;
               cal.add(Calendar.HOUR_OF_DAY, 1);
          }
          while (cal.get(Calendar.MONTH) != now.get(Calendar.MONTH)) {
               months++;
               cal.add(Calendar.MONTH, 1);
          }
          if (cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)) {
               months--;
               cal.add(Calendar.MONTH, -1);
          }
          while (cal.get(Calendar.DAY_OF_MONTH) != now.get(Calendar.DAY_OF_MONTH)) {
               days++;
               cal.add(Calendar.DATE, 1);
          }
          while (cal.get(Calendar.YEAR) < now.get(Calendar.YEAR)) {
               years++;
               cal.add(Calendar.YEAR, 1);
          }
          System.out.println("you are " + years + " years, " + months + " months " + days + " days "+
                hours+" hours "+mins+" minutes and "+secs+" seconds old");
0
 
CEHJCommented:
How are you defining 'birthday'?
0
 
objectsCommented:
> age.setTimeInMillis(Math.abs(birthday-System.currentTimeMillis()));

instead of doing that, take the number of millis, and do the maths to determine number of days etc.
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
armoghanAuthor Commented:
birthday is getting the time from date object
something like
Date e = 'some date'

long birthday = e.getTime();
0
 
armoghanAuthor Commented:
>> and do the maths to determine number of days etc.

Ahhh I hate maths :)
0
 
zzynxSoftware engineerCommented:
One problem with determining # years and # months starting from milliseconds:
How many days is one year? 365, 366?
How many days is one month? 28, 29, 30 or 31?
0
 
Giant2Commented:
You can do something like this:
with dd0, dd1 of type Calendar

      java.util.Calendar min=java.util.Calendar.getInstance();
      min.setTimeInMillis(dd0.getTimeInMillis()-dd1.getTimeInMillis());
0
 
Giant2Commented:
But the final conversion I believe is not really good.
You can try to convert the difference of milliseconds in Day Hour Min Sec...
And for resolving the 365-366 days you can see how many 366 days years are contained in the difference.
0
 
Giant2Commented:
for days in one month you can use a matching:
Gen 31
Feb 28 or 29 (if the division of the different is divisible for 4)
Mar 31
Apr 30
... and so on.

It's not easy, but not impossible.

Bye, Giant.
0
 
armoghanAuthor Commented:
Ahh Still no luck
I need something like

Mr X is 4 Years, 7 months, 31 days 10 hours 19 min 40 sec Old.

objects >> double days = (d2.getTime()-d1.getTime())/1000/60/60/24;
gives 1074 days
I need the days left after the months have been calculated.


>>>How many days is one year? 365, 366?
>>>How many days is one month? 28, 29, 30 or 31?

This is real issue. How can it be tackled?
What should I take a Month if I take 30 days a month
then from 8 th Jan to 8th sep it becomes 8 months and 4 days
That is what happens in the above posted code.


0
 
zzynxSoftware engineerCommented:
       Calendar cal = Calendar.getInstance();
        cal.set(1957, 5, 17);  // the birthday
        System.out.println("Since you're born on " +
            new SimpleDateFormat("dd MMMM yyyy").format(cal.getTime()));
        int years = 0;
        int months = 0;
        int days = 0;
        Date now = new Date();
       
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
       
        while ( cal.getTime().before(now) ) {
            cal.add(Calendar.DATE, 1);
            if ( cal.get(Calendar.YEAR) != year ) {
                years++;
                months = 0;
                days = 0;
                year = cal.get(Calendar.YEAR);
                continue;
            }
            if ( cal.get(Calendar.MONTH) != month ) {
                months++;
                days = 0;
                month = cal.get(Calendar.MONTH);
                continue;
            }
            days++;
        }
       
        System.out.println("you are " + years + " years, " + months + " months and " + days + " days old");

Output:
Since you're born on 17 juni 1957
you are 47 years, 9 months and 8 days old
0
 
armoghanAuthor Commented:
I am increasing the Points of this question. Lets see we get a better answer
0
 
armoghanAuthor Commented:
In zzynx code i put the starting date
cal.set(2004, 1, 8); // the birthday

And now it is showing me
you are 0 years, 7 months and 7 days old

the problem persists with days :(
0
 
Giant2Commented:
It could be more correct using add method of Calendar instead of use ++ over integer.

0
 
zzynxSoftware engineerCommented:
Please define:
from 6 sep to 6 oct is that one month? Also from 20 feb to 20 mar is that also 1 month? (no matter how much days feb has?)
0
 
Giant2Commented:
Try this:
            Calendar cal = Calendar.getInstance();
            cal.set(2004, 1, 8);  // the birthday remember the month start from 0
            System.out.println("Since you're born on " + new SimpleDateFormat("dd MMMM yyyy").format(cal.getTime()));
            int years = 0;
            int months = 0;
            int days = 0;
            Date now = new Date();

            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);

            while (cal.getTime().before(now)) {
                  while (cal.getTime().getDay()<now.getDay()){
                        days++;
                        cal.add(Calendar.DATE,1);
                  }
                  while (cal.getTime().getMonth()<now.getMonth()){
                        months++;
                        cal.add(Calendar.MONTH,1);
                  }
                  while (cal.getTime().getYear()<now.getYear()){
                        years++;
                        cal.add(Calendar.YEAR,1);
                  }
            }

            System.out.println("you are " + years + " years, " + months + " months and " + days + " days old");
0
 
Giant2Commented:
The result is:
Since you're born on 08 febrary 2004
you are 0 years, 7 months and 3 days old
0
 
zzynxSoftware engineerCommented:
I think he wants it to say:
Since you're born on 08 febrary 2004
you are 0 years, 7 months and 0 days old

Please confirm, armoghan.
0
 
zzynxConnect With a Mentor Software engineerCommented:
If you want:

    Since you're born on 08 februari 2004
    you are 0 years, 7 months and 0 days old
and
    Since you're born on 07 februari 2004
    you are 0 years, 7 months and 1 days old
and
    Since you're born on 09 februari 2004
    you are 0 years, 6 months and 30 days old    

This is the code:

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date now = cal.getTime();
        cal.set(2004, 1, 9);  // the birthday
        System.out.println("Since you're born on " +
            new SimpleDateFormat("dd MMMM yyyy").format(cal.getTime()));
        int years = 0;
        int months = 0;
        int days = 0;
        int theDay = cal.get(Calendar.DAY_OF_MONTH);
       
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
       
        while ( cal.getTime().before(now) ) {
            cal.add(Calendar.DATE, 1);
            if ( cal.get(Calendar.DAY_OF_MONTH) == theDay ) {
                months++;
                if (months==12) {
                    months = 0;
                    years++;
                }
                days = 0;
                continue;
            }
            days++;
        }
       
        System.out.println("you are " + years + " years, " + months + " months and " + days + " days old");
0
 
zzynxSoftware engineerCommented:
Remark:

You can remove the obsolete lines

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);

;)
0
 
armoghanAuthor Commented:
>>Since you're born on 08 febrary 2004
>>you are 0 years, 7 months and 0 days old

>> Please confirm, armoghan.

Yes, I think a person should be
 0 years, 7 months and 0 days old

0
 
zzynxSoftware engineerCommented:
Then see my last post
0
 
armoghanAuthor Commented:
Now which answer should be correct.
 Since you're born on 08 februari 2004

    you are 0 years, 7 months and 0 days old
    you are 0 years, 7 months and 3 days old
    you are 0 years, 6 months and 30 days old

BTW I am getting
6 months and 30 days old
from  zzynx last posted code

Sorry guys, I Got to go some where, will post the replies in the morning
0
 
Giant2Commented:
Ok.
So try this:
            Calendar cal = Calendar.getInstance();
            cal.set(2004, 1, 8); // the birthday remember the month start from 0
            System.out.println("Since you're born on " + new SimpleDateFormat("dd MMMM yyyy").format(cal.getTime()));
            int years = 0;
            int months = 0;
            int days = 0;
            Date now = new Date();
            while (cal.getTime().getDate() < now.getDate()) {
                  days++;
                  cal.add(Calendar.DATE, 1);
            }
            while (cal.getTime().getMonth() < now.getMonth()) {
                  months++;
                  cal.add(Calendar.MONTH, 1);
            }
            while (cal.getTime().getYear() < now.getYear()) {
                  years++;
                  cal.add(Calendar.YEAR, 1);
            }
            System.out.println("you are " + years + " years, " + months + " months and " + days + " days old");
0
 
Giant2Commented:
the answer is:
Since you're born on 08 febrary 2004
you are 0 years, 7 months and 0 days old
0
 
zzynxSoftware engineerCommented:
>> BTW I am getting
>> 6 months and 30 days old
>> from  zzynx last posted code

Of course!!!
Since that code contains:

              cal.set(2004, 1, 9);  // the birthday

You should change this to

              cal.set(2004, 1, 8);  // the birthday

to get:

         Since you're born on 08 februari 2004
         you are 0 years, 7 months and 0 days old

or change it to

         cal.set(2004, 1, 7);  // the birthday

to get

         Since you're born on 07 februari 2004
         you are 0 years, 7 months and 1 days old


Think you should reread my post ;°)

0
 
zzynxSoftware engineerCommented:
Giant,

1) You use deprecated functions getDate(), getMonth() & getYear()
2) Sure it works for 9 and 10 februari too?
0
 
objectsCommented:
following could be used to get # years, and the same concept extended to get other components:

http://www.javaalmanac.com/egs/java.util/GetAge.html
0
 
Giant2Connect With a Mentor Commented:
>2) Sure it works for 9 and 10 februari too?
Whoops. This is the correct code.


            Calendar cal = Calendar.getInstance();
            cal.set(2004, 1, 9); // the birthday remember the month start from 0
            System.out.println("Since you're born on " + new SimpleDateFormat("dd MMMM yyyy").format(cal.getTime()));
            int years = 0;
            int months = 0;
            int days = 0;
            Date now = new Date();
            while (cal.getTime().getDate() != now.getDate()) {
                  days++;
                  cal.add(Calendar.DATE, 1);
            }
            while (cal.getTime().getMonth() != now.getMonth()) {
                  months++;
                  cal.add(Calendar.MONTH, 1);
            }
            while (cal.getTime().getYear() < now.getYear()) {
                  years++;
                  cal.add(Calendar.YEAR, 1);
            }
            System.out.println("you are " + years + " years, " + months + " months and " + days + " days old");
0
 
zzynxSoftware engineerCommented:
>>Whoops. This is the correct code.
Sure? ;°)

It says:

Since you're born on 09 februari 2004 08:00:00
you are 0 years, 6 months and 28 days old

I think it should be 30 days:

9 feb to 9 aug = 6 months
10 aug            = 1 day
11 aug            = 2 days
...
31 aug            = 22 days
1 sep              = 23 days
2 sep              = 24 days
...
6 sep              = 28 days
7 sep              = 29 days
8 sep              = 30 days  (today is 8 sep)
0
 
CEHJCommented:
Age is often calculated using a 30 day month. See http://www.searchforancestors.com/utility/birthday.html
0
 
armoghanAuthor Commented:
Sorry zzynx,
I couldnot see your post correctly as i was in a hurry.

Ok I have changed Giant2 Code to this
/////////////////////////////////////////////////////////////////////////////////////////////////////
      Calendar cal = Calendar.getInstance();
//      if (timeCtrl.getValue() != null) {
//          dateCtrl.getCalendar().set(Calendar.HOUR,
//                                       timeCtrl.getCalendar().get(Calendar.HOUR));
//          dateCtrl.getCalendar().set(Calendar.HOUR_OF_DAY,
//                                       timeCtrl.
//                                       getCalendar().get(Calendar.HOUR_OF_DAY));
//          dateCtrl.getCalendar().set(Calendar.MINUTE,
//                                       timeCtrl.getCalendar().
//                                       get(Calendar.MINUTE));
//          dateCtrl.getCalendar().set(Calendar.SECOND,
//                                       timeCtrl.getCalendar().
//                                       get(Calendar.SECOND));
//          dateCtrl.getCalendar().set(Calendar.MILLISECOND,
//                                       timeCtrl.
//                                       getCalendar().get(Calendar.MILLISECOND));
//      }
//
//          cal.setTime(dateCtrl.getDate()); // the birthday

       cal.set(2004, Calendar.FEBRUARY, 9,11,50,0); // the birthday remember the month start from 0
      System.out.println("Giant2: Since you're born on " +
                         new SimpleDateFormat("dd MMMM yyyy HH:mm:ss").format(cal.
          getTime()));
      int years = 0;
      int months = 0;
      int days = 0;
      int hours = 0;
      int mins = 0;
      int secs = 0;
      Date now = new Date();
      while (cal.getTime().getDate() != now.getDate()) {
          days++;
          cal.add(Calendar.DATE, 1);
      }
      while (cal.getTime().getMonth() != now.getMonth()) {
          months++;
          cal.add(Calendar.MONTH, 1);
      }
      while (cal.getTime().getYear() < now.getYear()) {
          years++;
          cal.add(Calendar.YEAR, 1);
      }
      while (cal.getTime().getHours() < now.getHours()) {
          hours++;
          cal.add(Calendar.HOUR, 1);
      }
      while (cal.getTime().getMinutes() < now.getMinutes()) {
          mins++;
          cal.add(Calendar.MINUTE, 1);
      }
      while (cal.getTime().getSeconds() < now.getSeconds()) {
          secs ++;
          cal.add(Calendar.SECOND, 1);
      }



      System.out.println("Giant2 = you are " + years + " years, " + months +
                         " months and " + days + " days " + hours + " hours " + mins + " minutes "+ secs + " secs old");
 
/////////////////////////////////////////////////////////////////////////////////////////////////////

BTW I am taking, Time and Date in different controls, So in the commented code I am adding the Time part in the Date part. But I think it is not doing it correctly as well. cuz it still prints 0s in time when i display it using
System.out.println("Giant2: Since you're born on " +
                         new SimpleDateFormat("dd MMMM yyyy HH:mm:ss").format(cal.
          getTime()));


Now the problem is that the time with me is 9:00 AM and The time of birth is 11 Am, Which I have inputed on the top like
 cal.set(2004, Calendar.FEBRUARY, 9,11,50,0);

The day and every thing is same.
The result is
you are 0 years, 7 months and 0 days 0 hours 0 minutes 18 secs old
But I am not 7 months old unless it is 11 Am
I am 6 months 29 or 30 days and 22 Hr(s)  old


Same would be the case with zzynx method as well, if you add Hours and Minutes as well
How should it be cattered

Thank to all of you guys for giving me such valueable inputs
0
 
Giant2Connect With a Mentor Commented:
Now it works (with hour minutes and seconds):
Try this:

            Calendar cal = Calendar.getInstance();
            cal.set(2004, 1, 10,9,11,50); // the birthday remember the month start from 0
            System.out.println("Since you're born on " + new SimpleDateFormat("dd MMMM yyyy hh:mm:ss").format(cal.getTime()));
            int years = 0;
            int months = 0;
            int days = 0;
            int hours = 0;
            int mins = 0;
            int secs = 0;
            Calendar now = Calendar.getInstance();
            while (cal.getTime().getSeconds() != now.getTime().getSeconds()) {
                  secs++;
                  cal.add(Calendar.SECOND, 1);
            }
            while (cal.getTime().getMinutes() != now.getTime().getMinutes()) {
                  mins++;
                  cal.add(Calendar.MINUTE, 1);
            }
            while (cal.getTime().getHours() != now.getTime().getHours()) {
                  hours++;
                  cal.add(Calendar.HOUR_OF_DAY, 1);
            }
            while (cal.getTime().getMonth() != now.getTime().getMonth()) {
                  months++;
                  cal.add(Calendar.MONTH, 1);
            }
            if (cal.getTime().getDate()>now.getTime().getDate()){
                  months--;
                  cal.add(Calendar.MONTH, -1);
            }
            while (cal.getTime().getDate() != now.getTime().getDate()) {
                  days++;
                  cal.add(Calendar.DATE, 1);
            }
            while (cal.getTime().getYear() < now.getTime().getYear()) {
                  years++;
                  cal.add(Calendar.YEAR, 1);
            }
            System.out.println("you are " + years + " years, " + months + " months " + days + " days "+hours+" hours "+mins+" minutes and "+secs+" seconds old");
0
 
armoghanAuthor Commented:
Thanx a lot Giant2. Its working fine now.
Only one thing left, can we somehow remove the depricated methods from it.

zzynx, objects, CEHJ  can you help in this regard.

BTW I have solved the problem of Adding of Date and Time control into one dateTime, there was little bug.
0
 
zzynxSoftware engineerCommented:
>> Only one thing left, can we somehow remove the depricated methods from it.
I posted the above without having read this one ;°)
0
 
Giant2Commented:
>I posted the above without having read this one ;°)

Whow zzynx, you read in the mind!!

:)


Explaining:
replace all the cal.getTime().get...
with cal.get(...)
0
 
zzynxSoftware engineerCommented:
>>Whow zzynx, you read in the mind!!
:)
0
 
armoghanAuthor Commented:
Ohh I see another small problem.
I placed a time which is some minutes ahead of the current time, for same date in february.

e.g.
Since you're born on 09 February 2004 12:15:00 PM
Now it's 09 September 2004 12:10:31
The result was
you are 0 years, 6 months 30 days 23 hours 55 minutes and 31 seconds old

Now should it be 30 days old or 29 days.

To tackle this problem should we take the days only like
0 years, 210 days 23 hours 55 minutes and 31 seconds old
0
 
zzynxSoftware engineerCommented:
>>Since you're born on 09 February 2004 12:15:00 PM
>>Now it's 09 September 2004 12:10:31
>>The result was
>>you are 0 years, 6 months 30 days 23 hours 55 minutes and 31 seconds old
What's wrong with that?
That's the side-effect of wanting the age expressed in hours, minutes and seconds too.

>>Now should it be 30 days old or 29 days.
I can't link that with the earlier requirement. (age expressed in hours, minutes and seconds)
0
 
objectsCommented:
> zzynx, objects, CEHJ  can you help in this regard.

did u try the approach I suggested above

     Calendar dateOfBirth = new GregorianCalendar(1972, Calendar.JANUARY, 27);
   
    // Create a calendar object with today's date
    Calendar today = Calendar.getInstance();
   
    // Get age based on year
    int age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);
   
    // Add the tentative age to the date of birth to get this year's birthday
    dateOfBirth.add(Calendar.YEAR, age);
   
    // If this year's birthday has not happened yet, subtract one from age
    if (today.before(dateOfBirth)) {
        age--;
       dateOfBirth.add(Calendar.YEAR, -1);
    }

    // now do similiar to get number of months

    ....

    // then days etc
0
 
Giant2Commented:
agree with zzynx answer.

The difference between:
09 February 2004 12:15:00 PM
09 September 2004 12:10:31
is 0 years, 6 months 30 days 23 hours 55 minutes and 31 seconds
and not 7 months!
0
 
armoghanAuthor Commented:
Yes you are right
the answer is right
is 0 years, 6 months 30 days 23 hours 55 minutes and 31 seconds
and should not be 7 months.

But the problem is some months are of 30 days and some of 31.
With the answer given by the code i.e.
0 years, 6 months 30 days 23 hours 55 minutes and 31 seconds
shows that the durration of a month we select is of 31 days and as soon as the 31st day is completed we will increase 1 in months.
so if the answer would have been
0 years, 6 months 29 days 23 hours 55 minutes and 31 seconds
would it be correct as well ? - considering that we took month of 30 days


0
 
Giant2Commented:
?????
from 9 of august to 9 of september are 31 days.
Som if one day is not complete the duration is 30 days (not 29)!!

09 February12:15:00 PM
09 March12:15:00 PM
09April12:15:00 PM
09May12:15:00 PM
09June12:15:00 PM
09July12:15:00 PM
09 August12:15:00 PM
6 MONTHS
10 August12:15 PM
...
08 September12:15 PM
30 DAYS
...
09 September12:10:31
23 hours 55 minutes and 31 seconds

This is the count.
What count you do for obtaining 29 days??
0
 
zzynxSoftware engineerCommented:
>>so if the answer would have been
>>0 years, 6 months 29 days 23 hours 55 minutes and 31 seconds
>>would it be correct as well ?
Of course.
The way of calculating always takes the *real* number of days between - in this case -
9 aug and 9 sep.
0
 
zzynxSoftware engineerCommented:
In our code one month is
from the X th of month M to the X th of month M+1 (no matter how many days that is)
If no complete month is left, we count the *real* days.
0
 
zzynxSoftware engineerCommented:
>>>>so if the answer would have been
>>>>0 years, 6 months 29 days 23 hours 55 minutes and 31 seconds
>>>>would it be correct as well ?
>> Of course.
For some other birthday I mean of course!
0
 
armoghanAuthor Commented:
Ohh thanx got it..
Thank a lot for your help,
I appriciate it a lot.

I would split points with Giant2 and zzynx as they helped the most in obtaining teh solution.
I hope no objections :)

objects: I could not try out your way. Actually the problem is once you start getting the clues and ready made solutions, you start concentrating on them more .

0
 
zzynxSoftware engineerCommented:
>> I would split points with Giant2 and zzynx as they helped the most in obtaining teh solution
Sounds fair to me.
Please take care to select all the comments that helped you (for the people reading this afterwards)
0
 
objectsCommented:
> objects: I could not try out your way

Thats ok, its good to have it there anyway for the PAQ :)
0
 
zzynxSoftware engineerCommented:
Thanks for accepting.
0
 
Giant2Commented:
Thanks.
Happy to help you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.