计算两个时间段相差时长
public static String getDistanceTime(Long str1 ,Long str2) {
long day = 0;//天数差
long hour = 0;//小时数差
long min = 0;//分钟数差
long second=0;//秒数差
long diff=0 ;//毫秒差
StringBuilder result =new StringBuilder();
//String result = "";
diff = str2-str1;
day = diff / (24 * 60 * 60 * 1000);
hour = (diff / (60 * 60 * 1000) - day * 24);
min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
second = diff/1000;
System.out.println("day="+day+" hour="+hour+" min="+min+" ss="+second%60+" SSS="+diff%1000);
String daystr = day%30+"天";
String hourStr = hour%24+"小时";
String minStr = min%60+"分";
String secondStr = second%60+"秒";
if (day!=0){
result.append(daystr);
//result = result + daystr;
}
if (hour!=0){
result.append(hourStr);
//result = result + hourStr;
}
if (min!=0){
result.append(minStr);
//result = result + minStr;
}
if (second!=0){
result.append(secondStr);
//result = result + secondStr;
}
return result.toString();
}
创建主方法
public static void main(String[] args) throws ParseException {
String a="2023-07-27 14:43:00";
String b="2023-07-28 14:30:10";
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parse1 = dateFormat.parse(a);
Date parse2 = dateFormat.parse(b);
String bigDecimal=getDistanceTime(parse1.getTime(),parse2.getTime());
System.out.println(bigDecimal);
}
运行结果