Javascript 在24小时时钟上计算睡眠时间
首先,我要说我是HTML、Javascript等的初学者。 我正在制作一个闹钟,现在尝试添加一个功能,计算你必须睡觉的时间。 我使用的是24小时时钟格式,目前我有以下参数:Javascript 在24小时时钟上计算睡眠时间,javascript,date,time,Javascript,Date,Time,首先,我要说我是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 midni
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);
但这并不包括所有的选择
如果有人能解决这个问题,我将不胜感激
谢谢 你需要考虑到起床时间可能在早上,而当前时间可能在晚上,因此小时数不是一个简单的计算(尽管仍然可行)。您可以将唤醒时间转换为日期,并进行简单的日期比较。例如:
让wakeupat=new Date();
设定时间唤醒(32);
唤醒时间:设定分钟数(0);
设置秒时唤醒(0);
wakeupat.setms(0);
函数sleepLeving(){
让我们现在=新日期();
让diff=wakeupat-now;
如果(差异<0){
log(“唤醒!!!!”);
清除间隔(计时器);
}否则{
let剩余=新日期(差异);
log(剩余的.getHours()+“小时”+剩余的.getMinutes()+“分钟”和“+剩余的.getSeconds()+“秒”);
}
}
让定时器=设置间隔(剩余睡眠,1000)代码>请注意,小时数设置为24+8(=32)-即明天上午8点。更新为包含“唤醒!!”消息并停止计时器