簡體   English   中英

我如何從陣列中獲得下一次祈禱時間?

[英]How do i get next prayer time from array?

我正在嘗試使用當前時間從數組列表中獲取下一個即將到來的祈禱。

我正在使用 React Native

 prayer = [ { "name": "Fajr", "time": "2021-01-27T10:51:00.000000Z", }, { "id": 2, "name": "Dhuhr", "time": "2021-01-27T17:08:00.000000Z", }, { "id": 9, "name": "Asr", "time": "2021-01-27T19:45:00.000000Z", }, { "id": 10, "name": "Maghrib", "time": "2021-01-27T22:07:00.000000Z", }, { "id": 11, "name": "Isha", "time": "2021-01-27T23:26:00.000000Z", }, ]

謝謝您的幫助。

你可以做類似的事情var json = JSON.parse(prayer); let time = json.time; var json = JSON.parse(prayer); let time = json.time; 我沒有對此進行測試,但這應該可以

您可以使用 javascript 日期 object 並計算當前時間與每個日期之間的差異

一些粗略的代碼

const getDateObj = (time) => {
    let d = new Date(time)
    return d
}
let now = new Date()
let dif = getDateObj(prayer[0].time) - now;
let index = 0

for (let i = 0; i < prayer.length; i++) {
    const pray = prayer[i];
    const currentDif = (getDateObj(pray.time) - now)
    if ( currentDif < dif ){
        dif = currentDif;
        index = i
    }
}

console.log(prayer[index])

要獲得下一個祈禱時間,您需要執行以下步驟,如本例:

const getNextPrayer = () =>{
    //get current datetime in milliseconds
    const now = new Date().getTime();
    //Those variables will store the next prayer and its index
    var next ;
    var nextIndex ;
    //Loop through prayer array
    prayer.map((e,i)=>{
        //Convert prayer time to milliseconds
        var prayerTimeMilliseconds = new Date(e.time).getTime();
        //check if prayer time is not past
        if ((prayerTimeMilliseconds-now) >= 1){
          //get index of the smallest prayer time integer
          if (!next || (prayerTimeMilliseconds-now) < next){
                  next = prayerTimeMilliseconds-now
                  nextIndex = i
          }
        }
    })
    return nextIndex;
}

小吃的完整示例

暫無
暫無

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

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