Solved

Difference between 2 dates in Months rounded up to the nearest whole month

Posted on 2004-08-03
22
294 Views
Last Modified: 2010-03-31
Hey,

Anyone know how to get the difference between 2 dates in months rounded to the nearest whole month AND also include the fact that the start date will be set to midnight but the end date will be set to 11:59:59pm AND this should be counted as 1 day?

Thanks

Peter
0
Comment
Question by:peterwnorman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 9
  • 3
22 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 11704779
                       Calendar old = Calendar.getInstance();
                  old.setTime( date1 );

                  // set the calendar object representing the current date //
                  Calendar now = Calendar.getInstance();
                  now.setTime( date2 );

                  // get the difference between the 2 dates in milliseconds //
                  long difference = now.getTimeInMillis() - old.getTimeInMillis();

                  // set the calendar object representing the difference //
                  Calendar diff = Calendar.getInstance();
                  diff.setTimeInMillis(difference);

                  // print the difference //
                  System.out.println(diff.get(Calendar.MONTH) + " months" ) ;
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11704815
So you mean given date1 and date2, get the difference expressed in number of months.
+ date1 has always 00:00:00 as time and date2 always has 23:59:59 as time.
Right?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11704827
My comment assumes you have date1 and date2 which are both java.util.Date objects :-)
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
LVL 37

Expert Comment

by:zzynx
ID: 11704871
Hi Tim, quite close.
But does that "round to the nearest month"?
I don't think so.
0
 

Author Comment

by:peterwnorman
ID: 11704896
zznyx,

stated far more succinctly.

TimYates,

would your code handle month with 31 days in the way it would handle february (i.e. 1st feb to 2nd of Mar = 2 months; 1st of Mar to 31st of Mar = 1month)
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11704902
How can you round to the nearest month?

How many days is 0.5 months?  Surely it depends on the number of days in a month?

And the question says:

> rounded to the nearest whole month

Which I took to mean "round down" ;-)
0
 

Author Comment

by:peterwnorman
ID: 11704959
Sorry Tim,

Meant to say part months are counted as whole months.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11704992
Hmmm...actually...that code needs a bit of thought ;-)

it will give you a difference, but it will be a bit odd...  How many days are you taking as a month?  4 weeks, 31, 28, what?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11705006
So you want

date1=x-may-2004 00:00:00
date2=y-jun-2004 23:59:00

to return 1 if y <= x
and to return 2 if y > x

Right?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11705046
Can't it be done like this:

1) int result = 0;
2) Start by putting date1 in calendar.
3) Add one month and result++;
4) If the result is > date2
       return result;
    else
       goto 3) again
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11705092
Like this:

int result = 0;
Calendar cal = Calendar.getInstance();
cal.setTime( date1 );
while ( cal.getTime().before( date2 ) ) {
     result++;
     cal.add(Calendar.MONTH, 1);
}
return result;

(Didn't try it yet)
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11705103
import java.util.* ;
import java.text.* ;

public class DateTest
{
  public static void doDates( Date date1, Date date2 )
  {
    Calendar old = Calendar.getInstance() ;
    old.setTime( date1 ) ;

    // set the calendar object representing the current date //
    Calendar now = Calendar.getInstance() ;
    now.setTime( date2 ) ;

    int ret = 0 ;
    while( old.before( now ) )
    {
      old.add( Calendar.MONTH, 1 ) ;
      ret++ ;
    }

    System.out.println( ret + " months" ) ;
  }

  public static void main( String[] args )
  {
    try
    {
      SimpleDateFormat sdf = new SimpleDateFormat( "dd/MM/yyyy" ) ;
      doDates( sdf.parse( "01/02/2004" ), sdf.parse( "02/03/2004" ) ) ;
    }
    catch( ParseException ex )
    {
    }
  }
}
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11705111
LOL

Soz zzynx...
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11705122
great minds think alike....and I typed too much... ;-)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11705374
>> great minds think alike....and I typed too much... ;-)
:°)

It works, but it seems that the time of date2 must be set to 00:00:00 too, to get the correct results:

        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd HHmmss");
        Date date1 = null, date2 = null;
        try {
            date1 = fmt.parse("20040201 000000");        // <<<<<<<<<<<<< Here you can put in the dates you want to test
            date2 = fmt.parse("20040301 235959");        // <<<<<<<<<<<<< Here you can put in the dates you want to test
        } catch (ParseException ex) { }
       
        // date2 needs some tweaking
        Calendar calTmp = Calendar.getInstance();
        calTmp.setTime(date2);
        calTmp.set(Calendar.HOUR_OF_DAY, 0);
        calTmp.set(Calendar.MINUTE, 0);
        calTmp.set(Calendar.SECOND, 0);
        calTmp.set(Calendar.MILLISECOND, 0);
        date2 = calTmp.getTime();
       
        int result = 0;
        Calendar cal = Calendar.getInstance();
        cal.setTime( date1 );
        while ( !cal.getTime().after( date2 ) ) {
            result++;
            cal.add(Calendar.MONTH, 1);
        }
        System.out.println(result);

1-feb => 20-feb : 1
1-feb => 1-mar : 2
1-feb => 2-mar : 2
1-feb => 31-mar : 2
1-feb => 1-apr : 3
0
 
LVL 37

Accepted Solution

by:
zzynx earned 500 total points
ID: 11705389
Is that the way you want it peter?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11705578
Mmmm. °blush°

I retested and it seem to give the expected result without that date2 tweaking too.
So, it looks like you can remove these lines again:

        // date2 needs some tweaking
        Calendar calTmp = Calendar.getInstance();
        calTmp.setTime(date2);
        calTmp.set(Calendar.HOUR_OF_DAY, 0);
        calTmp.set(Calendar.MINUTE, 0);
        calTmp.set(Calendar.SECOND, 0);
        calTmp.set(Calendar.MILLISECOND, 0);
        date2 = calTmp.getTime();
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11705608
*giggle*
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11705610
;-)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11705727
>> *giggle*

Look to your other Q's, you naughty boy!
;°D
0
 

Author Comment

by:peterwnorman
ID: 11708145
zzynx,
that's the way I want it.

thanks (sorry about the delay responding. users wanted a demo).
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11712639
Great!
Thanks for accepting

(Although for the people after us reading this thread it would've been better to mark another comment as accepted answer)
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to get all the API from website? 11 161
JAVA API design with micro service cloud in mind 1 113
Website checklist for browser compatibility? 2 57
Java array sort 10 63
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

739 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