用java计算日期/时间差我也想计算两个日期之间的差额以小时/分钟/秒为单位。我的代码有一个小问题,就是:String dateStart = "11/03/14 09:29:58";String dateStop = "11/03/14 09:33:43";// Custom date formatSimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); Date d1 = null;Date d2 = null;try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);} catch (ParseException e) {
e.printStackTrace();} // Get msec from each, and subtract.long diff = d2.getTime() - d1.getTime();long diffSeconds = diff / 1000; long diffMinutes = diff / (60 * 1000); long diffHours = diff / (60 * 60 * 1000); System.out.println("Time in seconds: " + diffSeconds + " seconds."); System.out.println("Time in minutes: " + diffMinutes + " minutes."); System.out.println("Time in hours: " + diffHours + " hours.");这应产生:Time in seconds: 45 seconds.Time in minutes: 3 minutes.Time in hours: 0 hours.然而,我得到了这个结果:Time in seconds: 225 seconds.Time in minutes: 3 minutes.Time in hours: 0 hours.有人能看到我做错了什么吗?
3 回答
慕桂英546537
TA贡献1848条经验 获得超10个赞
long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000);
diff
慕神8447489
TA贡献1780条经验 获得超1个赞
java.util.concurrent.TimeUnit
long diff = d2.getTime() - d1.getTime();//as givenlong seconds = TimeUnit.MILLISECONDS.toSeconds(diff);long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
添加回答
举报
0/150
提交
取消