计算两个时间之间相隔天、小时、分、秒

/**

* @Description: 获取两个时间相差的天,时,分,秒
* @param str1 时间1

* @param str2 时间2

 *@ param  formmat 时间格式

* @return

*/
public static String differTime(String str1, String str2,String formmat) {
if (StringUtils.isBlank(str1) || StringUtils.isBlank(str2)) {
return "";
}
DateFormat df = new SimpleDateFormat(formmat);
Date one;
Date two;
long day = 0;
long hour = 0;
long min = 0;
long sec = 0;
try {
one = df.parse(str1);
two = df.parse(str2);
long time1 = one.getTime();
long time2 = two.getTime();
long diff;
if (time1 < time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
day = diff / (24 * 60 * 60 * 1000);
hour = (diff / (60 * 60 * 1000) - day * 24);
min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
} catch (ParseException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder("");
if (day != 0) {
sb.append(day + "天");
}
if (hour != 0) {
sb.append(hour + "小时");
}
if (min != 0) {
sb.append(min + "分");
}
if (min != 0) {
sb.append(sec + "秒");
}
return sb.toString();
}

你可能感兴趣的:(java,时间,时间差)