我的问题是如何计算到达特定时间需要多少小时和分钟。我的意思是如果我们有时间:15:32,我想计算到 05:32(晚上)需要多少小时,在这种情况下应该是 14 小时 32 分钟。
因为我真的没有那么多的知识和经验,所以我没有尝试过任何东西,因为我真的不知道从哪里开始。
const curDate = new Date().toLocaleTimeString();
console.log(curDate);
//I only know how to get the current date to string. But what next?
要获取到达一天中某个时间之前的小时和分钟,您应该执行以下步骤:
由于您是从另一个日期中减去一个日期,因此您无需进行任何转换(本地 => UTC)
const curDate = new Date(); // Step 1
const night = new Date(0, 0, 0, 5, 32); // Step 2
var hours = night.getHours() - curDate.getHours(); // Step 3a
if (hours < 0) hours += 24; // Step 3b
var minutes = night.getMinutes() - curDate.getMinutes(); // Step 4a
if (minutes < 0) { // Step 4b
hours -= 1;
minutes += 60;
}
console.log(["Hours: ", hours, ", Minutes: ", minutes].join(""));
以下是帮助您理解第 4 步的示例:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句