Solved

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

Posted on 2004-09-08
869 Views
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")+".");

0
Question by:armoghan
• 19
• 14
• 12
• +2

LVL 86

Expert Comment

How are you defining 'birthday'?
0

LVL 92

Expert Comment

> 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

LVL 18

Author Comment

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

long birthday = e.getTime();
0

LVL 92

Expert Comment

0

LVL 18

Author Comment

>> and do the maths to determine number of days etc.

Ahhh I hate maths :)
0

LVL 37

Expert Comment

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

LVL 12

Expert Comment

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

LVL 12

Expert Comment

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

LVL 12

Expert Comment

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

LVL 18

Author Comment

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

LVL 37

Expert Comment

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) ) {
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

LVL 18

Author Comment

I am increasing the Points of this question. Lets see we get a better answer
0

LVL 18

Author Comment

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

LVL 12

Expert Comment

It could be more correct using add method of Calendar instead of use ++ over integer.

0

LVL 37

Expert Comment

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

LVL 12

Expert Comment

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++;
}
while (cal.getTime().getMonth()<now.getMonth()){
months++;
}
while (cal.getTime().getYear()<now.getYear()){
years++;
}
}

System.out.println("you are " + years + " years, " + months + " months and " + days + " days old");
0

LVL 12

Expert Comment

The result is:
Since you're born on 08 febrary 2004
you are 0 years, 7 months and 3 days old
0

LVL 37

Expert Comment

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

0

LVL 37

Assisted Solution

zzynx earned 225 total points
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) ) {
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

LVL 37

Expert Comment

Remark:

You can remove the obsolete lines

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

;)
0

LVL 18

Author Comment

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

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

0

LVL 37

Expert Comment

Then see my last post
0

LVL 18

Author Comment

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

LVL 12

Expert Comment

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++;
}
while (cal.getTime().getMonth() < now.getMonth()) {
months++;
}
while (cal.getTime().getYear() < now.getYear()) {
years++;
}
System.out.println("you are " + years + " years, " + months + " months and " + days + " days old");
0

LVL 12

Expert Comment

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

LVL 37

Expert Comment

>> 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

LVL 37

Expert Comment

Giant,

1) You use deprecated functions getDate(), getMonth() & getYear()
2) Sure it works for 9 and 10 februari too?
0

LVL 92

Expert Comment

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

LVL 12

Assisted Solution

Giant2 earned 275 total points
>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++;
}
while (cal.getTime().getMonth() != now.getMonth()) {
months++;
}
while (cal.getTime().getYear() < now.getYear()) {
years++;
}
System.out.println("you are " + years + " years, " + months + " months and " + days + " days old");
0

LVL 37

Expert Comment

>>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

LVL 86

Expert Comment

Age is often calculated using a 30 day month. See http://www.searchforancestors.com/utility/birthday.html
0

LVL 18

Author Comment

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++;
}
while (cal.getTime().getMonth() != now.getMonth()) {
months++;
}
while (cal.getTime().getYear() < now.getYear()) {
years++;
}
while (cal.getTime().getHours() < now.getHours()) {
hours++;
}
while (cal.getTime().getMinutes() < now.getMinutes()) {
mins++;
}
while (cal.getTime().getSeconds() < now.getSeconds()) {
secs ++;
}

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

LVL 12

Assisted Solution

Giant2 earned 275 total points
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++;
}
while (cal.getTime().getMinutes() != now.getTime().getMinutes()) {
mins++;
}
while (cal.getTime().getHours() != now.getTime().getHours()) {
hours++;
}
while (cal.getTime().getMonth() != now.getTime().getMonth()) {
months++;
}
if (cal.getTime().getDate()>now.getTime().getDate()){
months--;
}
while (cal.getTime().getDate() != now.getTime().getDate()) {
days++;
}
while (cal.getTime().getYear() < now.getTime().getYear()) {
years++;
}
System.out.println("you are " + years + " years, " + months + " months " + days + " days "+hours+" hours "+mins+" minutes and "+secs+" seconds old");
0

LVL 18

Author Comment

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

LVL 37

Accepted Solution

zzynx earned 225 total points
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++;
}
while (cal.get(Calendar.MINUTE) != now.get(Calendar.MINUTE)) {
mins++;
}
while (cal.get(Calendar.HOUR_OF_DAY) != now.get(Calendar.HOUR_OF_DAY)) {
hours++;
}
while (cal.get(Calendar.MONTH) != now.get(Calendar.MONTH)) {
months++;
}
if (cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)) {
months--;
}
while (cal.get(Calendar.DAY_OF_MONTH) != now.get(Calendar.DAY_OF_MONTH)) {
days++;
}
while (cal.get(Calendar.YEAR) < now.get(Calendar.YEAR)) {
years++;
}
System.out.println("you are " + years + " years, " + months + " months " + days + " days "+
hours+" hours "+mins+" minutes and "+secs+" seconds old");
0

LVL 37

Expert Comment

>> Only one thing left, can we somehow remove the depricated methods from it.
I posted the above without having read this one ;Â°)
0

LVL 12

Expert Comment

>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

LVL 37

Expert Comment

>>Whow zzynx, you read in the mind!!
:)
0

LVL 18

Author Comment

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

LVL 37

Expert Comment

>>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

LVL 92

Expert Comment

> 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

// If this year's birthday has not happened yet, subtract one from age
if (today.before(dateOfBirth)) {
age--;
}

// now do similiar to get number of months

....

// then days etc
0

LVL 12

Expert Comment

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

LVL 18

Author Comment

Yes you are 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

LVL 12

Expert Comment

?????
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

LVL 37

Expert Comment

>>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

LVL 37

Expert Comment

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

LVL 37

Expert Comment

>>>>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

LVL 18

Author Comment

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

LVL 37

Expert Comment

>> 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

LVL 92

Expert Comment

> objects: I could not try out your way

Thats ok, its good to have it there anyway for the PAQ :)
0

LVL 37

Expert Comment

Thanks for accepting.
0

LVL 12

Expert Comment

Thanks.
0

## Featured Post

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a clâ€¦
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different dâ€¦
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arrâ€¦
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.