Heim > Fragen und Antworten > Hauptteil
Dies ist ein Foto des Fragments. Ich möchte eine Gebets-App erstellen, die Ihnen sagt, wie viel Zeit zwischen der aktuellen Zeit und der Gebetszeit verbleibt
Ich habe versucht, den Unterschied direkt dadurch zu finden
prayers = [[13,59], [13,30]]; let time = new Date(); let currprayer = new Date(); for (let index in prayers) { currprayer.setHours(prayers[index][0]) currprayer.setMinutes(prayers[index][1]) if (currprayer.getTime() > time.getTime()){ currprayer.setSeconds(00) let left = new Date(currprayer.getTime() - time.getTime() ); document.getElementById('nextmin').innerHTML = left.getMinutes() document.getElementById('nexthrs').innerHTML = left.getHours() document.getElementById('nextsec').innerHTML = left.getSeconds() } else{ console.log("nope") } }
<div class="details"> <div class="next-prayer"> <span id="nexthrs">00</span> <span>:</span> <span id="nextmin">00</span> <span>:</span> <span id="nextsec">00</span> </div> </div>
Aber es bleibt immer bei 00:00:00 hängen
P粉0990000442024-02-18 13:20:30
您可以获取两者的时间戳,将它们相减并将结果转换为新的日期格式,不是吗?检查链接来执行此操作: https://plainenglish.io/博客/如何将日期字符串转换为 JavaScript 中的时间戳
P粉0293277112024-02-18 00:54:55
问题是今天的时代可能已经成为过去。您的屏幕截图显示当地时间 19:24,这显然比 prayers
数组中的两个时间晚。在这种情况下,您应该查找第二天的时间。
如果在这种情况下您想在后一天下一次祈祷之前有时间,请在数组中再添加一个条目,其时间比第一个条目多 24 小时。为此,您必须首先确保时间按时间顺序列出(示例代码片段中的情况并非如此)
以下是您可以执行此操作的方法(请参阅代码中的注释):
// Always define variables with const/let. // Define the times in chronological order const prayers = [[1,59], [4,39], [6,49], [13,45], [17,33], [20,41], [22,42]]; // Add one more for the next day, that is 24 hours more than first entry prayers.push([prayers[0][0] + 24, prayers[0][1]]); function refresh() { const time = new Date(); const currprayer = new Date(); currprayer.setSeconds(0, 0); for (const prayer of prayers) { currprayer.setHours(...prayer); // Pass hours and minutes in one go if (currprayer > time) break; } const left = new Date(currprayer - time); // It's easier to format the time here and display it in one HTML element // We use UK locale just to make sure the time format is hh:mm:ss document.querySelector('.next-prayer').textContent = left.toLocaleTimeString("en-UK"); } // Start the interval timer setInterval(refresh, 200); // Also refresh the page immediately refresh();
<div class="details"> <div class="next-prayer"> </div> </div>