[引用链接](https://blog.csdn.net/xujiangdong1992/article/details/79006531
如果是String类型,需要转成date类型:
如:
String startTime = "2018-01-01 10:30:30";
String endTime = "2018-01-08 11:45:45";
//看自己的时间格式选择对应的转换对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
//转换成date类型
Date start = sdf.parse(startTime);
Date end = sdf.parse(endTime);
//获取毫秒数
Long startLong = start.getTime();
Long endLong = end.getTime();
//计算时间差,单位毫秒
Long ms = endLong-startLong;
//时间差转换为 \天\时\分\秒
String time = longTimeToDay(ms);
//转换函数,可以封装成公用方法
public static String longTimeToDay(Long ms){
Integer ss = 1000;
Integer mi = ss * 60;
Integer hh = mi * 60;
Integer dd = hh * 24;
Long day = ms / dd;
Long hour = (ms - day * dd) / hh;
Long minute = (ms - day * dd - hour * hh) / mi;
Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
StringBuffer sb = new StringBuffer();
if(day > 0) {
sb.append(day+"天");
}
if(hour > 0) {
sb.append(hour+"小时");
}
if(minute > 0) {
sb.append(minute+"分");
}
if(second > 0) {
sb.append(second+"秒");
}
if(milliSecond > 0) {
sb.append(milliSecond+"毫秒");
}
return sb.toString();
}
网友评论