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.
[codesyntax lang=”java5″]

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(String[] args) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
		try {
			Date date1 = simpleDateFormat.parse("10/10/2016 11:30:10");
			Date date2 = simpleDateFormat.parse("13/11/2017 20:35:55");
			// obj.printDifference(date1, date2);
			printDifference(date1, date2);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	public static void printDifference(Date startDate, Date endDate) {
		Interval interval = new Interval(startDate.getTime(), endDate.getTime());
		Period period = interval.toPeriod();
		System.out.println("  Start Date : " + startDate.toString());
		System.out.println("    End Date : " + endDate.toString());
		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());
	}
}

[/codesyntax]
The execution of the program is listed below.

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

Leave a Reply

Your email address will not be published. Required fields are marked *