Java教程

Java date日期类型,结束日期减去开始日期求两者时间差,精确到秒

本文主要是介绍Java date日期类型,结束日期减去开始日期求两者时间差,精确到秒,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/**
 * @Author:
 * @Description:
 * @Date: 2019/4/10 19:01
 * @Modified By:
 */
@Slf4j
public class DateUtils {

    private static final long nd = 1000 * 24 * 60 * 60;
    private static final long nh = 1000 * 60 * 60;
    private static final long nm = 1000 * 60;

    /**
     * 计算两个时间段时间差,精确到秒
     * @param startTime 2019-04-10 17:16:11
     * @param endTime 2019-04-10 17:28:17
     * @return
     */
    public static String computationTime(Date startTime, Date endTime){
        try {
            log.info("开始时间->{}, 结束时间->{}",startTime, endTime);
            long diff = endTime.getTime() - startTime.getTime();
            long day = diff / nd;
            long hour = diff % nd / nh;
            long min = diff % nd % nh / nm;
            long sec = diff % nd % nh % nm / 1000;
            String str = day + "天" + hour + "小时" + min + "分钟" + sec + "秒";
            return str;
        }catch (Exception e) {
            log.info("计算两个时间段时间差出错了, {}",e);
            return null;
        }
    }
}
这篇关于Java date日期类型,结束日期减去开始日期求两者时间差,精确到秒的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!