cancel
Showing results for 
Search instead for 
Did you mean: 

Duration in months between two dates

Former Member
0 Kudos

Hi .... plz help me solve the following -

Requirement -

Duaration in months between 2 Dates in Simple date Format

java.util.Date utilDate = new java.util.Date();

SimpleDateFormat todaysdate = new SimpleDateFormat("yyyy-MM-dd");

String date1 = todaysdate.format(utilDate);

I am using the above date format -

Using this how can I find the Difference between two Dates ("yyyy-MM-dd") in Simpla Date Format .

Waiting for some fast replies .

Thanks In Advance!!

Regards

Smita

Accepted Solutions (0)

Answers (2)

Answers (2)

Former Member
0 Kudos

Hello Smita,

first of all, I think you need to be a bit more precise when you say "duration in months":

What is your definition of the difference in months between

  • 2008-10-01 and 2008-10-31?

  • 2008-10-31 and 2008-11-01?

  • 2008-10-31 and 2008-11-30?

  • 2008-10-31 and 2008-12-01?

  • 2008-02-29 and 2009-02-28?

  • 2008-02-29 and 2009-03-01?

If your definition is what I consider the simplest one that says "completely ignore the days value" (so the answers to the questions above would be 0, 1, 1, 2, 12 and 13), then I would compute that value without the use of any java.util.* classes (which is good for performance, too; Date and Calendar are quite heavyweight):


public int getDifferenceInMonths(String date1, String date2) { // dates in "yyyy-MM-dd" format
  int year1 = Integer.parseInt(date1.substring(0, 4));
  int year2 = Integer.parseInt(date2.substring(0, 4));
  int month1 = Integer.parseInt(date1.substring(5, 7));
  int month2 = Integer.parseInt(date2.substring(5, 7));
  return 12 * (year2 - year1) + month2 - month1;
}

Depending on whether you want the absolute value of the difference, you can put a Math.abs() around the return value.

Does that help?

Regards,

Jens

snehal_kendre
Active Contributor
0 Kudos

HI,

why dont use calender..

	Date d1 = new GregorianCalendar(2008, 9, 31, 23, 59).getTime();

	    /** Today's date */
	    Date today = new Date();
	    System.out.println(d1);
	    // Get msec from each, and subtract.
	    long diff = today.getTime() - d1.getTime();
	    System.out.println(diff / (1000 * 60 * 60 * 24));

it will give you diff in dates

but as you have asked Difference between two Dates ("yyyy-MM-dd") in Simpla Date Format .

right now i dont have a solution for this..