BCS Java Date Difference

There are may solution to Java challenges. Today our challenge surrounds calculating elapsed years, months, days, hours, minuets and seconds between two dates.

The primary workhorse for this task is JodaTime utility. Click on the Releases option and the Downloads sub option to download jars and utilities. Simply add the downloaded jar to tour Java project and you are ready for action.

package dtt;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.joda.time.Interval;
import org.joda.time.Period;
 
public class ft {
 
	public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) {
 
		1.5.0/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat simpleDateFormat = new 1.5.0/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat("dd/M/yyyy hh:mm:ss");
 
		try {
 
			5+0%2Fdocs%2Fapi+Date">Date date1 = simpleDateFormat.parse("10/10/2016 11:30:10");
			5+0%2Fdocs%2Fapi+Date">Date date2 = simpleDateFormat.parse("13/11/2017 20:35:55");
 
			// obj.printDifference(date1, date2);
			printDifference(date1, date2);
 
		} catch (1.5.0/docs/api/java/text/ParseException.html">ParseException e) {
			e.printStackTrace();
		}
	}
 
	public static void printDifference(5+0%2Fdocs%2Fapi+Date">Date startDate, 5+0%2Fdocs%2Fapi+Date">Date endDate) {
 
		Interval interval = new Interval(startDate.getTime(), endDate.getTime());
		Period period = interval.toPeriod();
 
		1.5.0/docs/api/java/lang/System.html">System.out.println("  Start Date : " + startDate.toString());
		1.5.0/docs/api/java/lang/System.html">System.out.println("    End Date : " + endDate.toString());
		1.5.0/docs/api/java/lang/System.html">System.out.printf("Elapsed Time : " + "%d years, %d months, %d days, %d hours, %d minutes, %d seconds%n", period.getYears(),
				period.getMonths(), period.getDays(), period.getHours(), period.getMinutes(), period.getSeconds());
	}
}

The execution of the program is listed below.

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

Leave a Reply