我有一个时钟输入和时钟输出时间以HH / MM / SS格式存储在我的程序中作为字符串。如何计算两者之间的小时,分钟和秒的差异?如果有必要,我可以将这两个转换回日期,但不能为我的生活找出如何计算差异!
e.g。
clockIn = 12:10:45 clockout = 14:10:50
timeDiff应该是02:00:15。
提前致谢。
答案 0 :(得分:2)
一旦你有两个日期,你可以getTime()以毫秒为单位获得时间:
long date1Ms = clockIn.getTime();
long date2Ms = clockOut.getTime();
long difference = date1Ms - date2Ms;
一旦你有了Ms的差异,转换为小时/分钟/秒很容易:
int hoursDiff = (int) (difference / (60 * 60 * 1000));
int hoursMs = hoursDiff * 60 * 60 * 1000;
int minsDiff = (int) ((difference - hoursMs) / (60 * 1000));
int minsMs = hoursMs + minsDiff * 60 * 1000;
int secDiff = (int) ((difference - minsMs) / 1000);
在这里,hoursDiff,minsDiff和secDiff为您提供所需的细分。
答案 1 :(得分:0)
你可以做这样的事情来实现时差
SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");
Date d1 = sdf.parse("12:10:45");
Date d2 = sdf.parse("14:10:50");
long diff = Math.abs(d1.getTime() - d2.getTime());
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
System.out.println(diffHours+":"+diffMinutes+":"+diffSeconds);
希望这有帮助。