Java日期时间差异

时间:2012-04-24 06:09:14

标签: java

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值是。

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

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

2 个答案:

答案 0 :(得分: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.

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

答案 1 :(得分: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.");