实现思路:利用两个日期值(年月日时分秒,如:2022-02-28 10:57:12与2022-02-18 16:25:40),先对此格式日期转换为时间戳格式,再通过换算,得到两个日期差值:10天5小时26分。
JS代码:
//计算两个时间差 返回天小时分钟
function timediff(begin_time, end_time){
//年月日时分秒转换为时间戳
let beginTime = (new Date(begin_time).getTime()) / 1000;
let endTime = (new Date(end_time).getTime()) / 1000;
var starttime = ''
var endtime = ''
if (beginTime < endTime) {
starttime = beginTime;
endtime = endTime;
} else {
starttime = endTime;
endtime = beginTime;
//计算天数
var timediff = endtime - starttime;
var days = parseInt(timediff / 86400);
//计算小时数
var remain = timediff % 86400;
var hours = parseInt(remain / 3600);
//计算分钟数
var remain = remain % 3600;
var mins = parseInt(remain / 60);
var res = days + '天' + hours + '小时' + mins + '分';