CALCULATE DIFFERENCE BETWEEN TWO DATES

This program calculates the difference between two dates. This difference which is basically in milliseconds is then converted into the number of days, hours, minutes and seconds.

package samples;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DifferenceBetweenTwoDates{
public static void main(String[] args) {
String dateStart = “01/14/2012 09:29:58”;
String dateStop = “01/15/2012 10:31:48”;

// HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat(“MM/dd/yyyy HH:mm:ss”);

Date d1 = null;
Date d2 = null;

try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);

// in milliseconds
long diff = d2.getTime() – d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println(“realdifference : ” + diff);
System.out.print(diffDays + ” days, “);
System.out.print(diffHours + ” hours, “);
System.out.print(diffMinutes + ” minutes, “);
System.out.print(diffSeconds + ” seconds.”);

} catch (Exception e) {
e.printStackTrace();
}

}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s