首页 > 解决方案 > 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!

标签: javascriptdatetime

解决方案


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);


推荐阅读