Calculating Difference In Months For Two Dates



package com.kushal.util;

/**
 * @(#)KpCalendar.java
 * @author Kushal Paudyal (kushalzone@gmail.com)
 * @version 1.00 2007/4/18
 * www.sanjaal.com/java
 */

import java.util.*;

public class KPCalendar {

	/**Default Constructor**/
	public KPCalendar() {
	}

	public double monthDifference(String calString1, String calString2)
	{
		double difference =0;

		try{
			Calendar cal1=new GregorianCalendar();
			Date time1=new Date(calString1);

			cal1.setTime(time1);

			Calendar cal2=new GregorianCalendar();
			Date time2=new Date(calString2);
			cal2.setTime(time2);

			long time1Millis=cal1.getTimeInMillis();
			long time2Millis= cal2.getTimeInMillis();

			double d1=((double)time1Millis)/(1000*60*60*24);
			double d2=((double)time2Millis)/(1000*60*60*24);
			System.out.println(d1);
			System.out.println(d2);

			difference=Math.round(Math.abs((d1-d2)/30));
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Error Occurred");
		}
		finally{
			System.out.println(difference);
			return difference;
		}
	}

	/** Testing for the functionality of the method **/
	public static void main(String args [])
	{
		KPCalendar util=new KPCalendar();
		util.monthDifference("04/01/2007","08/5/2007");
	}
}

Blog Widget by LinkWithin

Originally posted 2007-09-13 15:53:25.

Share
Tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to Calculating Difference In Months For Two Dates

  1. guitargod1 says:

    Very well! Are you dudes agree with me? When I read it I was like: oh man!Sounds great! This is just what I was searching for! All is true, and checked, I’m sure.

Leave a Reply