# Date manipulation

Hi Experts,

I'm given two dates, date1 and date2. Date1 is the earlier date.
What is the best way, using Java API,

a)to find the number of days between date1 and date2
b)to find the number of months between date1 and date2
c)to find the number of years between date1 and date2

Thanks
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Software engineerCommented:
Date date1 = ...;
Date date2 = ...;

int years = 0;
int months = 0;
int days = 0;
Calendar biggest = Calendar.getInstance();
biggest.setTime(date2);
Calendar smallest = Calendar.getInstance();
smallest.setTime(date1);

while (smallest.get(Calendar.MONTH) != biggest.get(Calendar.MONTH)) {
months++;
}
if (smallest.get(Calendar.DAY_OF_MONTH) > biggest.get(Calendar.DAY_OF_MONTH)) {
months--;
}
while (smallest.get(Calendar.DAY_OF_MONTH) != biggest.get(Calendar.DAY_OF_MONTH)) {
days++;
}
while (smallest.get(Calendar.YEAR) < biggest.get(Calendar.YEAR)) {
years++;
}
System.out.println("The difference between " + new SimpleDateFormat("dd MMMM yyyy").format(date1) +
" and " +  new SimpleDateFormat("dd MMMM yyyy").format(date2) );
System.out.println("is " + years + " years, " + months + " months and " + days + " days ");
0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Author Commented:
Thanks..

Any other ways that are simpler from anyone? Or any other ways?
0
Software engineerCommented:
still simpler? ;°)
0
Commented:
That's the best way
0
Commented:
Well... I'm not quite sure. :^)
You can just get the number of milliseconds from both dates, subtract them, and split them by some values.
e.g.: int daysDiff = (int) ((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24))
0
Commented:
>>You can just get the number of milliseconds from both dates ...

No, since that won't take into account adjustments due to daylight saving time. zzynx's code will
0
Software engineerCommented:
>> You can just get the number of milliseconds from both dates
If you're going to count the months this way too, how many days will "one month" be? 28, 29, 30 or 31?
My code uses the real number of days per month.
0
Commented:
Sure, you're right. My method can be used to count the number of days.
0
Commented:
>>My method can be used to count the number of days

It can, but may not do it right, for the reason i've already given
0
Commented:
Fine. But did the author of the question wanted to get the difference between two dates in years, months and days - all three at the same time? Or just the quickest method to get such differences separately (difference in years, difference in months, difference in days)? I guess it's the second case (- right?).
0
Software engineerCommented:
>> differences separately
Then he can still use 3x my code and omit the while's he doesn't need.
0
Commented:
What's the difference between march 2005 and january 2003? 2 months and 2 years? Or 26 month?
Now you see what I mean? If he omits the while's he doesn't need, the answer will be simple: 2 months. ;-)
0
Commented:
Since the difference in days is the one that is indisputable as far as calculation is concerned, you should calculate that per zzynx and calculate the others from that according to rules acceptable to yourself
0
Commented:
You won't be able to count the difference in days using zzynx method. Unless you take the lower date, and will shift the days until you get the bigger date. But I think it's not the most effective way of solving this task.
0
Software engineerCommented:
>> If he omits the while's he doesn't need, the answer will be simple: 2 months.
I meant an **intelligent** omit of course ;°)

Assume you're just interested in # months:

Calendar cal = Calendar.getInstance();
cal.set(2003, 0, 1, 23, 0, 0); // january 2003
Date date1 = cal.getTime();
cal.set(2005, 2, 1, 5 , 12 , 5);  // march 2005
Date date2 = cal.getTime();

int months = 0;
Calendar biggest = Calendar.getInstance();
biggest.setTime(date2);
Calendar smallest = Calendar.getInstance();
smallest.setTime(date1);

while (smallest.get(Calendar.MONTH) != biggest.get(Calendar.MONTH)) {
months++;
}
if (smallest.get(Calendar.DAY_OF_MONTH) > biggest.get(Calendar.DAY_OF_MONTH)) {
months--;
}
while (smallest.get(Calendar.YEAR) < biggest.get(Calendar.YEAR)) {
months+=12;
}
System.out.println("The difference between " + new SimpleDateFormat("dd MMMM yyyy").format(date1) +
" and " +  new SimpleDateFormat("dd MMMM yyyy").format(date2) );
System.out.println("is " + months + " months");

This prints:

The difference between 01 januari 2003 and 01 maart 2005
is 26 months
0
Commented:
Sure. Months were simple. Now do it for days. :-)
0
Software engineerCommented:
Hey, man you talked about months.

>> Now do it for days
Just add day by day until date1 equals date2 and that's it.
0
Commented:
int diff = dateDifference(d1, d2, Calendar.DAY);
diff = dateDifference(d1, d2, Calendar.MONTH);
diff = dateDifference(d1, d2, Calendar.YEAR);

.......

public int dateDifference(Date d1, Date d2, int period)
0
Commented:
> Just add day by day until date1 equals date2 and that's it.

Is it supposed to be the most effective algorithm?

> public int dateDifference(Date d1, Date d2, int period)

That's pretty. Now the body of this method... :-)
0
Software engineerCommented:
>> Is it supposed to be the most effective algorithm?
Certainly the most correct, as extensively explained already.
Up to ricjava, now.
0
Commented:
>int daysDiff = (int) ((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24))
>> No, since that won't take into account adjustments due to daylight saving time.

BTW, Date.getTime returns number of milliseconds since January 1, 1970, 00:00:00 GMT.
0
Commented:
Even better: use Calendar.getTimeInMillis
(returns the current time as UTC milliseconds from the epoch.)
0
Commented:
>>That's pretty. Now the body of this method... :-)

I'm sure you can fill that in along these lines:

if (smallest.get(period) > biggest.get(period))
0
Commented:
> I'm sure you can fill that in along these lines:
>        if (smallest.get(period) > biggest.get(period))

Hmm. Do you want to say you have no slightest idea how to implement this method?
(no offence - it's probably my English, not good enough to understand your little riddles...)
0
Commented:
0
Commented:
> http://www.javaalmanac.com/egs/java.util/CompDates.html
> long diffDays = diffMillis/(24*60*60*1000);  // 7

Look - it's my solution! *grin*
0
Commented:
sorry mate, missed it wading thru all the crap :)
0
Commented:
>>
Even better: use Calendar.getTimeInMillis
(returns the current time as UTC milliseconds from the epoch.)
>>

That's perfectly ok if you're working in UTC and you want a time difference that doesn't use real world time involving daylight saving
0
Commented:
time zones and daylight savings are really irrelevant
0
Commented:
>>time zones and daylight savings are really irrelevant

Why?
0
Commented:
A day is the same no matter what timezone you are in.
0
Commented:
Not so much the timezone that's the problem, it's daylight saving. e.g. clocks get put forward and back one hour
0
Commented:
daylight saving is part of the timezone, it can be ignored.
0
Author Commented:
hi, i'm back. It was weekend and i didn't have access.

thanks for all comments and i'm looking them
0
Author Commented:
hi zzynx -  It seems that the first comment of yours will produce negative months and days. For eg. if date1 is 21/03/1974 and date2 is 15/02/1981. At the end of your println statement, u will have negative month and day. do u notice?

0
Software engineerCommented:
>> It seems that the first comment of yours will produce negative months and days
For me it doesn't. It says:

The difference between 21 march 1974 and 15 february 1981
is 6 years, 10 months and 25 days

Can you post the code that you use?
0
Software engineerCommented:
This is the code *I* use:

Calendar cal = Calendar.getInstance();
cal.set(1974, 2, 21); // 21 march 1974
Date date1 = cal.getTime();
cal.set(1981, 1, 15); // 15 feb 1981
Date date2 = cal.getTime();

followed by the code I posted in my first comment
0
Commented:
The only operation he does on days is incrementation...
So, how it may get negative? 8-|
0
Author Commented:
let me try again....:)
0
Software engineerCommented:
How are things going, ricjava?
0
Author Commented:
yup zzynx - the date works accurate!
0
Software engineerCommented:
Good :°)
0
Software engineerCommented:
Thenk kindly close this Q by accepting
0
Author Commented:
any problem?
0
Commented:
Unfair. It was my solution...
I'll report this one.
0
Software engineerCommented:
Thanks for accepting
I agree with Maruszewski: he was the first to mention the difference in milliseconds.
0
Author Commented:
actually, i knew how to get the milliseconds.
Object provided the answer to the requirement of my question. I ask for the difference in years or months or days.
Since, along the way, I was interested in zzynx's solution and got some replies, points for him too.
0
Software engineerCommented:
>> Object provided the answer to the requirement of my question. I ask for the difference in years or months or days.
I can't see that in that link.
It just talks about milliseconds, seconds, minutes, hours and days. Not about months or years.

Moreover, in his following comment
>> sorry mate, missed it wading thru all the crap :)
objects gives credit to RMaruszewski...

0
Commented:
Thanks, zzynx.
0
Software engineerCommented:
No problem, mate. That's just how it is.
0
Commented:
zzynx,

>  I ask for the difference in years or months or days.
zzynx>> Not about months or years.

it says *or*, not *and*
0
Software engineerCommented:
>> it says *or*, not *and*
It's not because he accepted my first comment (which deals with the *and*) that I didn't provide the *or*.
But to see that you have to wade through all the crap of course...
0
Software engineerCommented:
But, that was an offence to my comments.
0
Software engineerCommented:
Silence is golden...
0
Commented:
> Silence is golden...

You should check someone is listening to you before you go carrying on.
0
Author Commented:
Dear all,

Let's look  at my original question carefully. I was asking about date1 and date2 where date2 was later date. From the question, I implied that I want to get the difference between the two dates in a) in days or b) in months or c) in years

comment from zzynx
>> Object provided the answer to the requirement of my question. I ask for the difference in >>years or months or days.
>>I can't see that in that link.
>>It just talks about milliseconds, seconds, minutes, hours and days. Not about months or >>years.
From the days, i could get months and years (although it may not be overly accurate, months can be 28, 29, 30, 31 and year can be 365, 366. If date1 and date2 difference is by thousand years then it won't be accurate if i divide by 365.). I got quite some information from that link http://www.javaalmanac.com/egs/java.util/CompDates.html
That's why I gave Objects 50pts.

I also gave zzynx 50 pts for his answer. He provided *and* answer but from the and answer I could also get the *or*. And I guess the accurate *or*.

The reason I gave objects and zzynx 50 pts each is because either answers were somewhat a solution.

As for RMaruszewski, yes he was the first one who gave the difference in milliseconds and he  has put lots of effort in my question. I was lost in the craps too as I was spotting for the obvious to my eyes. Also I'm quite new in awarding points in the midst of many comments, which should I award - the first who gave contributions, solutions only or all significant contributions.

0
Commented:
sorry for all the commotion, some do take their points very seriously.
(Personally I don't mind what you do, they are your points after all.)
0
Author Commented:
no worries, btw, if i were to award points to all who contributed, then CEHJ also comes into my mind. He assured me that zzynx's way was the best way
>That's the best way

0
Commented:
>That's the best way

thats got to be worth points :)
0
Software engineerCommented:
ricjava,
But since both the answers of RMaruszewski and objects were rather identical, common sense expected that you
or
But at last you're the boss ;°)

>> Also I'm quite new in awarding points in the midst of many comments, which should I award
See the EE help pages. They say e.g.:

If a comment posted by an Expert has answered your question, then you should select the Expert's comment as the answer to your question. In case of duplicate or similar comments, you should select the first comment posted. Often your answer and or solution may be up to the Author of the question, as many solutions work differently than others depending on their circumstances or preferences should there be a grey area.

Sometimes one EE Expert will post a comment which answers your question but contains a typo or minor error. Another Expert may post a correction. In this case you should usually select the answer of the first Expert. If you would like to reward the second Expert, you can split the points.

>> some do take their points very seriously. (Personally I don't mind what you do
LOL
A fairplay reacting on RMaruszewski's answer would have been better in trying to convince us about that.
0
Commented:
> As for RMaruszewski, yes he was the first one who gave the difference in milliseconds

I was also the first who gave difference in days. Read the answers carefully.
And don't call our comments "crap". I'm learning a lot from this "crap", even if you are not able to see any value of it.
0
Author Commented:
zzynx, will u defend me for the "crap" word?
0
Commented:
>>zzynx, will u defend me for the "crap" word?

It's not zzynx who should be defending himself for quoting this insult, but the person who used it in the first place ;-)
0
Software engineerCommented:
>> zzynx, will u defend me for the "crap" word?
Don't understand what you're trying to say...

>> It's not zzynx who should be defending himself for quoting this insult, but the person who used it in the first place ;-)
Very right you are CEHJ!
0
Author Commented:
Dear All,

Just look at the beginning after i had awarded the points.

>>any problem

That indicates my willingness to discuss/negotiate about my points award. Otherwise i won't bother to ask *any problem*

I suggest the points to be
zzynx 34
RMaruszewski 33
Objects 33

Note: Awarding Objects 33 points because of the link that he gave me and for the
>>time zones and daylight savings are really irrelevant
comment

Ah, will the system allow such points to be entered?
As for CEHJ, since I have only 100 pts for the question, any suggestion of points awards from anyone? Is 25 pts the minimum allowed by the system? To award all with 25 pts  may not be fair.

Well, I need to explain something.
As for the word *crap*, let look at all the occurences of it in this thread.

First occurence
>>sorry mate, missed it wading thru all the crap :)

Second occurence
>>>> it says *or*, not *and*
>>It's not because he accepted my first comment (which deals with the >>*and*) that I didn't provide the *or*.
>>But to see that you have to wade through all the crap of course...

Third occurence (This time it is from me)
>>I was lost in the craps too as I was spotting for the obvious to my >>eyes.

I use the word *craps* only on the third occurence in this thread and I was not the first or second person who used it. Even though english is not my first language, I believe that when both of them used the word *crap*, they didn't mean anything disdainful. I think it was rather an *informal expressions* in everyday languages. Since they use it, I believe they won't mind anybody using it. When I use that word "craps", it was only an echo. I echo it for a kind of communication style.

I have to explain it because someone excuse me of insult.
Someone speaks for RMaruszewski but why no one speaks for me :(
0
Author Commented:
Dear Admin - if required, I can raise the points to rectify. I tried to explain why I awarded the point. Nevertheless, I didn't say I was perfectly right or fair in points award

Thanks
0
Commented:
>>As for CEHJ,

0
Author Commented:

I suggest
zzynx - 125
RMaruszewski - 100
objects - 100
cehj - 75

Any objections?

0
Commented:
Thanks :)
0
Author Commented:
no problem
0
Software engineerCommented:
Thanks ricjava.
As I already said: for me the points you gave were OK.
0
Commented:
8-)
0
Commented:
Thank you.

The points don't really matter (and the stake wasn't so high, either).
But it's the competition, after all. That's what makes EE so much fun, and so different from typical discussion groups, isn't it?
So if I give the fastest and most accurate answer, I want to take credit for it. But it's not about any virtual points...