[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Date manipulation

Posted on 2004-11-26
78
Medium Priority
?
2,861 Views
Last Modified: 2012-06-21
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
0
Comment
Question by:ricjava
  • 21
  • 16
  • 15
  • +2
74 Comments
 
LVL 37

Accepted Solution

by:
zzynx earned 500 total points
ID: 12679520
         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++;
               smallest.add(Calendar.MONTH, 1);
          }
          if (smallest.get(Calendar.DAY_OF_MONTH) > biggest.get(Calendar.DAY_OF_MONTH)) {
               months--;
               smallest.add(Calendar.MONTH, -1);
          }
          while (smallest.get(Calendar.DAY_OF_MONTH) != biggest.get(Calendar.DAY_OF_MONTH)) {
               days++;
               smallest.add(Calendar.DATE, 1);
          }
          while (smallest.get(Calendar.YEAR) < biggest.get(Calendar.YEAR)) {
               years++;
               smallest.add(Calendar.YEAR, 1);
          }
          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
 

Author Comment

by:ricjava
ID: 12679589
Thanks..

Any other ways that are simpler from anyone? Or any other ways?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12679614
still simpler? ;°)
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 300 total points
ID: 12679925
That's the best way
0
 
LVL 3

Assisted Solution

by:RMaruszewski
RMaruszewski earned 400 total points
ID: 12680004
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 12680018
>>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
 
LVL 37

Expert Comment

by:zzynx
ID: 12680043
>> 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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12680242
Sure, you're right. My method can be used to count the number of days.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12680272
>>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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12680889
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12681013
>> differences separately
Then he can still use 3x my code and omit the while's he doesn't need.
0
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12681242
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 12681263
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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12681321
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12681335
>> 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++;
               smallest.add(Calendar.MONTH, 1);
          }
          if (smallest.get(Calendar.DAY_OF_MONTH) > biggest.get(Calendar.DAY_OF_MONTH)) {
               months--;
               smallest.add(Calendar.MONTH, -1);
          }
          while (smallest.get(Calendar.YEAR) < biggest.get(Calendar.YEAR)) {
               months+=12;
               smallest.add(Calendar.YEAR, 1);
          }
          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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12681391
Sure. Months were simple. Now do it for days. :-)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12681431
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 12681433
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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12681482
> 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
 
LVL 37

Expert Comment

by:zzynx
ID: 12681536
>> Is it supposed to be the most effective algorithm?
Certainly the most correct, as extensively explained already.
Up to ricjava, now.
0
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12681693
>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.
You don't need any adjustments.
0
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12681813
Even better: use Calendar.getTimeInMillis
(returns the current time as UTC milliseconds from the epoch.)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12683181
>>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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12683248
> 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
 
LVL 92

Assisted Solution

by:objects
objects earned 400 total points
ID: 12684068
0
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12684128
> http://www.javaalmanac.com/egs/java.util/CompDates.html
> long diffDays = diffMillis/(24*60*60*1000);  // 7

Look - it's my solution! *grin*
0
 
LVL 92

Expert Comment

by:objects
ID: 12684161
sorry mate, missed it wading thru all the crap :)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12684181
>>
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
 
LVL 92

Assisted Solution

by:objects
objects earned 400 total points
ID: 12684197
time zones and daylight savings are really irrelevant
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12684209
>>time zones and daylight savings are really irrelevant

Why?
0
 
LVL 92

Expert Comment

by:objects
ID: 12684221
A day is the same no matter what timezone you are in.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12684229
Not so much the timezone that's the problem, it's daylight saving. e.g. clocks get put forward and back one hour
0
 
LVL 92

Expert Comment

by:objects
ID: 12684237
daylight saving is part of the timezone, it can be ignored.
0
 

Author Comment

by:ricjava
ID: 12694132
hi, i'm back. It was weekend and i didn't have access.

thanks for all comments and i'm looking them
0
 

Author Comment

by:ricjava
ID: 12694773
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12694848
>> 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
 
LVL 37

Expert Comment

by:zzynx
ID: 12694863
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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12694872
The only operation he does on days is incrementation...
So, how it may get negative? 8-|
0
 

Author Comment

by:ricjava
ID: 12694937
let me try again....:)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12705881
How are things going, ricjava?
0
 

Author Comment

by:ricjava
ID: 12713940
yup zzynx - the date works accurate!
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12714021
Good :°)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12714029
Thenk kindly close this Q by accepting
0
 

Author Comment

by:ricjava
ID: 12723616
any problem?
0
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12723651
Unfair. It was my solution...
I'll report this one.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12723692
Thanks for accepting
I agree with Maruszewski: he was the first to mention the difference in milliseconds.
0
 

Author Comment

by:ricjava
ID: 12723747
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12724066
>> 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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12724179
Thanks, zzynx.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12724185
No problem, mate. That's just how it is.
0
 
LVL 92

Expert Comment

by:objects
ID: 12724199
zzynx,

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

it says *or*, not *and*
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12724254
>> 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
 
LVL 37

Expert Comment

by:zzynx
ID: 12724285
But, that was an offence to my comments.
The real question was about RMaruszewski's comment. What about that?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12724334
Silence is golden...
0
 
LVL 92

Expert Comment

by:objects
ID: 12730969
> Silence is golden...

You should check someone is listening to you before you go carrying on.
0
 

Author Comment

by:ricjava
ID: 12733147
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.

Have your say, anyone?
0
 
LVL 92

Expert Comment

by:objects
ID: 12733206
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 Comment

by:ricjava
ID: 12733239
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
 
LVL 92

Expert Comment

by:objects
ID: 12733249
>That's the best way

thats got to be worth points :)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12733936
ricjava,
YOU decide what answers did help you most. Those deserve your points. Your explanation about that is very acceptable.
But since both the answers of RMaruszewski and objects were rather identical, common sense expected that you
- awarded the first answer
or
- awarded both answers
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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12734006
> 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 Comment

by:ricjava
ID: 12734219
zzynx, will u defend me for the "crap" word?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12735049
>>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
 
LVL 37

Expert Comment

by:zzynx
ID: 12736549
>> 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 Comment

by:ricjava
ID: 12743351
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 Comment

by:ricjava
ID: 12743398
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 12743717
>>As for CEHJ,

Don't worry about me ;-)
0
 

Author Comment

by:ricjava
ID: 12750814
Thanks Admin,

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

Any objections?

0
 
LVL 92

Expert Comment

by:objects
ID: 12751443
Thanks :)
0
 

Author Comment

by:ricjava
ID: 12751444
no problem
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12751823
Thanks ricjava.
As I already said: for me the points you gave were OK.
>> YOU decide what answers did help you most. Those deserve your points.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12752609
8-)
0
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12752707
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...
It's about the <b>self-satisfaction</b>. ;-)
0
 

Author Comment

by:ricjava
ID: 12760364
welcome.

And yes to uphold competitiveness is important.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month18 days, 12 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question