Skip Navigation Links

Tips for Java Software Developers

The tips on this web site were written by Eric Bergman-Terrell. They cannot be republished without the author's permission.

© Copyright 2004 Eric Bergman-Terrell
All Rights Reserved
Eric Bergman-Terrell & Levi Pop a Wheelie

  1. Date Manipulation
    1. How to calculate the number of days between two dates
    2. How to validate a date
  2. Execute a Command-Line Program
    1. How to execute a command-line program synchronously

Date Manipulation


How to calculate the number of days between two dates

Be sure to call clear() on the date1 and date2 arguments before setting them. Otherwise their hours, minutes, and seconds values will be set to the current time. Remember that months are zero-based when you set the date1 and date2 arguments.

private long differenceInDays(Calendar date1, Calendar date2)
{
	final long msPerDay = 1000 * 60 * 60 * 24;
		
	final long date1Milliseconds = date1.getTime().getTime();
	final long date2Milliseconds = date2.getTime().getTime();
	final long result = (date1Milliseconds - date2Milliseconds) / msPerDay;
		
	return result;
}

How to validate a date

This function verifies that the date specified by the year, month, and day is a valid date.

private static boolean dateIsValid(int year, int month, int day)
{
	boolean result = true;

	try
	{		
		// Want to force USA date formatting so that the month, day, and year
		// are not interpreted differently if this software is run in a different
		// locale!
		DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
		df.setLenient(false);
			
		final String dateString = month + "/" + day + "/" + year;
		df.parse(dateString);
	}
	catch (Exception e)
	{
		result = false;
	}
		
	return result;
}

Execute a Command-Line Program


How to execute a command-line program synchronously

The Runtime class has an exec method that will call a command-line executable, but it is run asynchronously. You can force your Java program to wait for the program to complete by calling the waitFor method of the Process object that is returned by the exec call:

public class Test
{

	public static void main(String[] args)
	{
		System.out.println("Before Call");
		
		Runtime r = Runtime.getRuntime();
		
		try
		{
			// Call the command-line program.
			Process p = r.exec("C:/JavaExecTest/bin/Debug/JavaExecTest.exe ARG1 ARG2 ARG3");

			// Wait for it to complete.
			p.waitFor();
			
			// Get program's exit code.
			final int exitValue = p.exitValue();
			
		}
		catch (Exception ex)
		{
			System.out.println("Caught exception " + ex.getMessage());
		}

		System.out.println("After Call");
	}
}


Home Page   Shareware   C# .NET Tips   Download C# .NET Source Code   Browse C# .NET Source Code   C# .NET Open Source   On-Line Utilities   Blog   Contact