javascript - Calculating sleep time on a 24-hour clock
问题描述
I'll start by saying that i'm a beginner with HTML, Javascript and so on. I'm building an alarm clock and now trying to add a feature that calculates the time you have to sleep. I'm using a 24-hour clock format, and at the moment I have these parameters:
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.
So the user can choose an 'hour' to wake up (24 options), and 'minutes' (12 options).
The problem i'm having is with calculating the time the user has to sleep from the time 'now' :
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.";
At first I tried
let tempSleepHours = Math.abs(tempWakeUpHour - hourNow);
let tempSleepMins = Math.abs(tempWakeUpMin - minNow);
but that doesn't cover all the options.
I'd appreciate it if anyone has the solution for this.
Thanks!
解决方案
You need to take into account that the wakeup time will likely be in the morning and the current time could be in the evening, so hours wouldn't be a straightforward calculation (though still doable). What you could do is convert the wakeup time into a date and do a simple date comparison. For example:
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);
推荐阅读
- docker - 使用 docker 在分布式模式下运行 karate-gatling 测试
- reactjs - React 测试库:对象作为 React 子级无效
- php - 椭球面积函数没有给出正确的结果
- html - v-dialog vuetify vueJS 中的高度
- .net - 为什么选择查询会陷入死锁?
- c++ - 未定义的参考 C++ 和 openMPI
- javascript - 如何通过控制台接收数据中的数据 - VueJs?
- linux - 将目录上传到 aws EC2 linux 服务器失败
- node.js - LDAP 身份验证失败
- angular - form.valid 对于自定义字段组件始终为真