繁体   English   中英

以 24 小时制计算睡眠时间

[英]Calculating sleep time on a 24-hour clock

我首先要说我是 HTML、Javascript 等方面的初学者。 我正在构建一个闹钟,现在尝试添加一个功能来计算你必须睡觉的时间。 我使用的是 24 小时制时钟格式,目前我有以下参数:

let tempWakeUpHour;  //stores the 'hours' value that the user chooses in a 00 format. (01 means 01:00, 02 means 02:00, and so on, 23 means 23:00 and 24 means midnight).

let tempWakeUpMin;  //stores the 'minutes' value that the user chooses in a 00 format and has only the options of 00, 05, 10, 15, and up to 55. 

因此,用户可以选择“小时”唤醒(24 个选项)和“分钟”(12 个选项)。

我遇到的问题是计算用户从“现在”时间开始睡觉的时间:

let dateNow = new Date();
let hourNow = dateNow.getHours();
let minNow = dateNow.getMinutes();
let tempSleepHours;  **// should calculate the hours left to sleep.**
let tempSleepMins;  **// should calculate the minutes left to sleep.**

...innerHTML = "you have " + tempSleepHours + " hours and " + tempSleepMins + " minutes to sleep.";

起初我试过

let tempSleepHours = Math.abs(tempWakeUpHour - hourNow);
let tempSleepMins = Math.abs(tempWakeUpMin - minNow); 

但这并没有涵盖所有选项。

如果有人对此有解决方案,我将不胜感激。

谢谢!

您需要考虑到唤醒时间可能在早上,而当前时间可能在晚上,因此小时数不是一个简单的计算(尽管仍然可行)。 您可以做的是将唤醒时间转换为日期并进行简单的日期比较。 例如:

 let wakeupat = new Date(); wakeupat.setHours(32); wakeupat.setMinutes(0); wakeupat.setSeconds(0); wakeupat.setMilliseconds(0); function sleepremaining() { let now = new Date(); let diff = wakeupat - now; if (diff < 0) { console.log("Wake up!!!!"); clearInterval(timer); } else { let remaining = new Date(diff); console.log(remaining.getHours() + " hours " + remaining.getMinutes() + " minutes and " + remaining.getSeconds() + " seconds"); } } let timer = setInterval(sleepremaining, 1000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM