Rohit Haval
Rohit Haval

Reputation: 149

Java date-time difference

long d1Ms = current_date.getTime();
long d2Ms = last_time.getTime();
long diff = Math.abs((d1Ms - d2Ms) / 60000);
System.out.println("d1MS: " + d1Ms);
System.out.println("d2MS: " + d2Ms);
System.out.println("Time difference (abs): " + diff)

my current_date & last_time values are.

current_date: Tue Apr 24 11:07:22 IST 2012
last_time:    Mon Apr 23 04:11:48 IST 2012

it displays time difference:1855 but it should be less than 1440 because duration is less than 24 hrs.why it so? and what is the solution to get proper difference?

Upvotes: 0

Views: 765

Answers (2)

Khalid Habib
Khalid Habib

Reputation: 1156

//Here is an other solution to calculate the time difference

String dateLastModified     = "01/14/2012 09:29:58";   
String dateCurrent          = "01/15/2012 10:31:48";

//Formate your time and date
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

java.util.Date date1        = null;
java.util.Date date2        = null;
//parse the values from String to date
date1   = format.parse(dateLastModified);
date2   = format.parse(dateCurrent);

//time in  milliseconds
long timeDiff = date2.getTime() - date1.getTime();

    long diffSeconds = timeDiff / 1000 % 60;
    long diffMinutes = timeDiff / (60 * 1000) % 60;
    long diffHours = timeDiff / (60 * 60 * 1000) % 24;
    long diffDays = timeDiff / (24 * 60 * 60 * 1000);

    System.out.print(diffDays + " days, ");
    System.out.print(diffHours + " hours, ");
    System.out.print(diffMinutes + " minutes, ");
    System.out.print(diffSeconds + " seconds.");

Upvotes: 0

Serdalis
Serdalis

Reputation: 10489

1855 is the correct answer:

11:07:22 - 04:11:48 == ~31 hours == 1855 minutes.

11am on the 23rd - 24 hours is
11am on the 22nd - ~7 hours is
4am on the 22nd which is your second date.

Your solution should work fine.

Upvotes: 5

Related Questions