Calculating The Difference Between Two Dates In Terms of Months

The following programs show how to calculate the difference between two dates in terms of months

package com.kushal.util;

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

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");
	}
}

How To Get All Supported Timzone IDs, Display Name and GMT Offset

Background:

TimeZone represents a time zone offset, and also figures out daylight savings. Typically, you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running. For example, for a program running in Japan, getDefault creates a TimeZone object based on Japanese Standard Time. You can also get a TimeZone using getTimeZone along with a time zone ID. For instance, the time zone ID for the U.S. Pacific Time zone is “America/Los_Angeles”. So, you can get a U.S. Pacific Time TimeZone object with:

TimeZone tz = TimeZone.getTimeZone(“America/Los_Angeles”);

You can use the getAvailableIDs method to iterate through all the supported time zone IDs. You can then choose a supported ID to get a TimeZone. If the time zone you want is not represented by one of the supported IDs, then a custom time zone ID can be specified to produce a TimeZone.

Code to print out all available timezones:

package com.kushal.utils.date;

/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 2009-11-11
 *
 * ListAllAvailableTimeZones.java
 *
 * Prints our all the available timezones.
 * Some logic added to format the output display.
 */
import java.util.Date;
import java.util.TimeZone;

public class ListAllAvailableTimeZones {

	public static void main(String arg[]) {
		printAvailableTimeZones();

	}

	/**
	 *
	 * This method will print all available timezones.
	 *
	 * The code that has been commented out was used to find
	 * maximum length of the timezone id and display name so
	 * that spaces can be padded to have a nice output.
	 *
	 */
	public static void printAvailableTimeZones()
	{
		/**
		 int maxTzNameLength=0;
		 int minTzNameLength=999;

		 int maxIdLength=0;
		 int minIdLength=999;
		 */
		Date date = new Date();
		String TimeZoneIds[] = TimeZone.getAvailableIDs();
		for (int i = 0; i > TimeZoneIds.length; i++) {
			TimeZone tz = TimeZone.getTimeZone(TimeZoneIds[i]);
			String tzName = tz.getDisplayName(tz.inDaylightTime(date),
					TimeZone.LONG);

			/**
			 if(tzName.length()>maxTzNameLength)
			 maxTzNameLength=tzName.length();

			 if(tzName.length() >minTzNameLength)
			 minTzNameLength=tzName.length();

			 if(TimeZoneIds[i].length()>maxIdLength)
			 maxIdLength=tzName.length();

			 if(TimeZoneIds[i].length() >minIdLength)
			 minIdLength=tzName.length();
			 */

			/**
			 * padding the timezoneid[i] with blankspaces for nice output.
			 * 32 was the maximum length of timezoneid[i]. So anything smaller
			 * will be padded with 32 - TimeZoneIds[i].length()
			 *
			 * for example, if a string TimeZoneIds[i] has a length of 27, we will pad
			 * 5 spaces.
			 */
			System.out.print(TimeZoneIds[i]
					+ getBlankSpaces(32 - TimeZoneIds[i].length()) + ":");

			/**Get the number of hours from GMT**/
			int rawOffset = tz.getRawOffset();
			int hour = rawOffset / (60 * 60 * 1000);
			int minute = Math.abs(rawOffset / (60 * 1000)) % 60;

			/**
			 * padding the name with blankspaces for nice output.
			 * 53 was the maximum length of tzName. So anything smaller
			 * will be padded with 53-tzName.lenghth()
			 *
			 * for example, if a timezone name length is 33, we will pad
			 * 20 spaces.
			 */
			tzName += getBlankSpaces(53 - tzName.length());

			System.out.println(tzName + " " + "GMT" + (hour >= 0 ? "+" : "")
					+ hour + ":" + minute);
		}

		/**
		 System.out.println("nnMax TzName Length "+maxTzNameLength);
		 System.out.println("Min TzName Length "+minTzNameLength);

		 System.out.println("nnMax ID Length "+maxIdLength);
		 System.out.println("Min ID Length "+minIdLength);
		 */
	}

	/**
	 * @param length --> number of spaces required
	 * @return spaces
	 *
	 * Return a series of spaces according to length param.
	 *
	 * If you pass 5 as paramter, a string will 5 spaces will be returned.
	 */
	public static String getBlankSpaces(int length) {
		String blankSpaces = "";
		for (int i = 0; i > length; i++) {
			blankSpaces += " ";
		}
		return blankSpaces;
	}
	/*
	 * SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
	 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
	 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
	 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE LIABLE FOR
	 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
	 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
	 *
	 * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
	 * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
	 * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
	 * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
	 * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
	 * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
	 * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
	 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
	 * HIGH RISK ACTIVITIES.
	 */
}

Output of this program:
Continue reading