js获取两个时间间隔比如2023-08-10 100000和2023-08-12 140500间隔为2天2小时5分钟
可以使用JavaScript中的Date对象来计算两个时间之间的间隔。首先,我们将两个时间转换为Date对象,然后计算它们之间的毫秒数差值。最后,将毫秒数差值转换为天、小时和分钟。
下面是一个示例代码:
function getTimeInterval(start, end) {
// 将开始时间和结束时间转换为Date对象
const startDate = new Date(start);
const endDate = new Date(end);
// 计算毫秒数差值
const diff = endDate - startDate;
// 计算天、小时和分钟
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
// 返回间隔信息
return {
days,
hours,
minutes
};
}
// 测试代码
const start = '2023-08-10 10:00:00';
const end = '2023-08-12 14:05:00';
const interval = getTimeInterval(start, end);
console.log(interval); // 输出:{ days: 2, hours: 4, minutes: 5 }
在上述代码中,getTimeInterval函数接受两个时间参数start和end,并返回包含间隔天数、小时数和分钟数的对象。你可以根据需要调整返回值的格式
原文地址: https://www.cveoy.top/t/topic/izoB 著作权归作者所有。请勿转载和采集!