Java工具类 计算某个时间距离当前时间相差多少天、多少小时、多少分、多少秒

/**
 * 计算传入时间距离当前时间多久
 *
 * @param date
 * @return
 */
public static String getTimeDiff(String date) {
    if (ObjectUtils.isEmpty(date)) {
        return "";
    }
    StringBuilder sb = new StringBuilder();
    try {
        Date parse = mDateFormat.parse(date);
        Date now = new Date();
        // 这样得到的差值是微秒级别
        long diff = now.getTime() - parse.getTime();
        // 只能精确到日 无法具细到年 月 不能确定一个月具体多少天 不能确定一年具体多少天
        // 获取日
        long day = diff / (1000 * 60 * 60 * 24);
        diff = diff % (1000 * 60 * 60 * 24);
        if (day > 0) {
            sb.append(day).append("天");
        }
        // 获取时
        long hour = diff / (1000 * 60 * 60);
        diff = diff % (1000 * 60 * 60);
        if (hour > 0) {
            sb.append(hour).append("时");
        }
        // 获取分
        long min = diff / (1000 * 60);
        diff = diff % (1000 * 60);
        if (min > 0) {
            sb.append(min).append("分");
        }
        // 获取秒
        long sec = diff / 1000;
        if (sec > 0) {
            sb.append(sec).append("秒");
        }
        return sb.toString();
    } catch (ParseException e) {
        return "";
    }
}

你可能感兴趣的:(JavaEE,工具类,计算时间差,java)