0
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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I've retrieved both the values from database tables.and 23rd april's time was 4 PM not AM and 24 april is 11AM.So I am not getting why is it so?
04:11:48 is 4am in 24 hour time, 16:11:48 is 4pm.
Thanks for quick reply, The problem was in values of tables..values which i was inserting in tables through cal.gettime() were in two different formats(12hrs and 24hrs) so after retrieval it was displaying wrong output.
Interesting, so the values you inserted were in 12 hour time and the values you retrieved were in 24 hour time? Time is a bitch if you're not careful, no doubt.
Yeah,Just like that... one should always check for capital H and small h while setting the format of time otherwise above problem persists.
0

//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.");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.