這是片段的照片我想創建一個祈禱應用程序,它可以告訴您當前時間與祈禱時間之間還剩多少時間
我試圖透過這樣做直接找到差異
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>
但它一直卡在 00:00:00
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>