我必须找到两个不同日期之间的时间差异 我试试这个:
Date d1 = null;
Date d2 = null;
d1 = format.parse(startDate);
d2 = format.parse(endDate);
long diff = d2.getTime() - d1.getTime();
diffSeconds = diff / 1000 % 60;
diffMinutes = diff / (60 * 1000) % 60;
diffHours = diff / (60 * 60 * 1000);
但是当我将startDate
设置为2017年5月15日23:40:10和endDate
至2017年5月16日00:05:55
输出是:
diffSeconds = -15;
diffMinutes = -25;
diffHours = -23;
我怎么能解决这个问题?谢谢。
答案 0 :(得分:0)
您在日期格式中犯了错误,或者您已经切换了开始日期和结束日期。
以下完美无缺:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String startDate = "15/05/2017 23:40:10";
String endDate = "16/05/2017 00:05:55";
Date d1 = format.parse(startDate);
Date d2 = format.parse(endDate);
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
System.out.println(diffHours + " " + diffMinutes + " " + diffSeconds);
输出是:
0 25 45