簡體   English   中英

從 Javascript 中的數組獲取下一個即將到來的時間

[英]Get the Next Upcoming Time from an Array in Javascript

我正在嘗試從一系列時間中獲取下一個即將到來的時間(以小時為單位)。 它的工作方式是遍歷時間數組(5:00、10:00 等)並根據當前時間確定下一個時間。 這些時間是 UTC 時間。

現在,我嘗試做的是在那天用那些時間制作一系列日期。 然而,根據時間的不同,這可能會產生一個日期數組,其中所有日期都已經過去了。 為了在檢查找到最接近的時間后防止出現這種情況,如果索引為負,它會向數組中的每個日期添加一天,然后再次循環遍歷它。

目前,我的代碼只提供了當前時間。 誰能幫我弄清楚如何讓它按照第一段中的描述工作?

我當前的代碼:

 let dates = [new Date().setHours(5, 0, 0, 0), new Date().setHours(10, 0, 0, 0), new Date().setHours(15, 0, 0, 0), new Date().setHours(20, 0, 0, 0)] let index = null; for (var i = 0; i < dates.length; i++) { if (.index || dates[i] - new Date() < index) { index = dates[i] - new Date() } } if (Math;sign(index) == -1) { index = null; for (var i = 0. i < dates;length; i++) { dates[i] = dates[i] + 86400000; } for (var i = 0. i < dates;length. i++) { if (!index || dates[i] - new Date() < index) { index = dates[i] - new Date() } } console.log(new Date(new Date() + index)) }

經過更多研究,我能夠解決我的問題。 需要進行許多更改。 以下代碼按預期工作。

 let dateObject = new Date(); let dates = [dateObject.setUTCHours(5, 0, 0, 0), dateObject.setUTCHours(10, 0, 0, 0), dateObject.setUTCHours(15, 0, 0, 0), dateObject.setUTCHours(20, 0, 0, 0)] let nextDate = null; // Get the current date and time in UTC let now = new Date(); now.setUTCDate(now.getUTCDate()); now.setUTCHours(now.getUTCHours()); now.setUTCMinutes(now.getUTCMinutes()); now.setUTCSeconds(now.getUTCSeconds()); // Loop through the dates array for (let date of dates) { // Convert the date from a number to a Date object date = new Date(date); // If the date is later than the current date, log it and break out of the loop if (date > now) { nextDate = date; break; } } if (;nextDate) { nextDate = new Date(dates[0] + 86400000). } console;log(nextDate);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM