簡體   English   中英

Javascript:在數組中獲取與當前時間匹配的日期范圍的對象

[英]Javascript: Get object with date range in array which matches to the current time

如果已經在 Stack 上問過這個問題,請糾正我,但我沒有找到任何可以解決我的問題的答案。 我只想顯示數組的對象,其中由timeStarttimeEnd組成的日期范圍與當前時間匹配。 假設當前時間是2020-10-22T16:35:45+01:00 ,該函數應該顯示Steve (參見下面給出的示例)它的約會。 如何搜索當前時間在給定日期范圍之間的對象?

const currentTime = Date.now(); // 2020-10-22T16:35:45+01:00

這是我正在使用的數組:

[
    {
        name: "Thomas",
        timeStart: "2020-10-22T16:00:00+0100",
        timeEnd: "2020-10-22T16:15:00+01:00"
    },
    {
        name: "Marc",
        timeStart: "2020-10-22T16:15:00+0100",
        timeEnd: "2020-10-22T16:30:00+01:00"
    },
    {
        name: "Steve",
        timeStart: "2020-10-22T16:30:00+0100",
        timeEnd: "2020-10-22T16:45:00+01:00"
    }
]

這對你有用嗎? 它搜索每個日期並確保當前日期介於開始和結束之間。

 const currentTime = Date.now(); // 2020-10-22T16:35:45+01:00 const dates = [{ name: "Thomas", timeStart: "2020-10-22T16:00:00+0100", timeEnd: "2020-10-22T16:15:00+01:00" }, { name: "Marc", timeStart: "2020-10-22T16:15:00+0100", timeEnd: "2020-10-22T16:30:00+01:00" }, { name: "Steve", timeStart: "2020-10-22T16:30:00+0100", timeEnd: "2020-10-22T16:45:00+01:00" } ]; // If you want only one result, use find instead of filter const validDates = dates.filter((obj) => { // Converts strings to Dates let startDate = new Date(obj.timeStart); let endDate = new Date(obj.timeEnd); // Makes sure the current time is after the start date and before the end date return currentTime >= startDate && currentTime <= endDate; }); console.log(validDates); // To get name, use validDates[0].name (for filter, see above) or validDates.name (for find)

它會是這樣的:

const currentTime = Date.now();

const resultArray=yourArray.filter(item=>{
      // you have to format dates to be able to compare them
      return item.timeStart < currentTime && item.timeEnd > currentTime
      });

比較find循環中的開始、結束和當前日期。
如果比較返回 true 則返回當前對象,否則返回undefined

 const now = new Date("2020-10-22T16:17:00+01:00"); // 16:17. Should be Marc. const dates = [ { name: "Thomas", timeStart: "2020-10-22T16:00:00+0100", timeEnd: "2020-10-22T16:15:00+01:00" }, { name: "Marc", timeStart: "2020-10-22T16:15:00+0100", timeEnd: "2020-10-22T16:30:00+01:00" }, { name: "Steve", timeStart: "2020-10-22T16:30:00+0100", timeEnd: "2020-10-22T16:45:00+01:00" } ]; const result = dates.find(({ timeStart, timeEnd }) => { const start = new Date(timeStart); const end = new Date(timeEnd); return start <= now && end > now; }); console.log(result);

試試這樣 yourArray.filter(item => currentTime >= item.timeStart && currenttime <= timeEnd)

暫無
暫無

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

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