2012-04-24 93 views
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) 

我current_date & last_time值是。Java日期时间差

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

它显示时间差:1855但它应该小于1440因为持续时间少于24小时,为什么呢?什么是解决方案来获得适当的区别?

回答

5

1855是正确答案:

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. 

您的解决方案应该能正常运行。

+0

我检索到的无论是从数据库tables.and 4月23日的时间值是下午4点不AM和4月24日是11AM.So我我不明白为什么会这样? – 2012-04-24 06:41:51

+2

'04:11:48'在'24小时时间'是'4点','16:11:48'是'4点'。 – Serdalis 2012-04-24 06:43:06

+1

感谢您的快速回复,问题是表格值..我通过cal.gettime()插入表中的值有两种不同的格式(12小时和24小时),所以检索后显示错误的输出。 – 2012-04-24 07:10:46

0

//这里是一个其他的解决办法,以计算时间差

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