【问题标题】:How do i get next prayer time from array?我如何从阵列中获得下一次祈祷时间?
【发布时间】:2021-01-31 07:28:58
【问题描述】:

我正在尝试使用当前时间从数组列表中获取下一个即将到来的祈祷。

我使用 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",
  },
]

感谢您的帮助。

【问题讨论】:

  • 你自己试过了吗?
  • 我尝试了一些方法,但根本不起作用。
  • 作为一般建议,SO 用户喜欢看到您的尝试及其结果。我们不是来编写您的代码,而是帮助您编写代码。

标签: javascript arrays react-native momentjs


【解决方案1】:

你可以做这样的事情 var json = JSON.parse(prayer); let time = json.time; 我没有对此进行测试,但这应该可以工作

【讨论】:

  • 我可以显示祈祷时间,但我想使用当前时间接近即将到来的祈祷
【解决方案2】:

您可以使用javascript日期对象并计算当前时间与每个日期之间的差异

一些粗略的代码

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])

【讨论】:

    【解决方案3】:

    要获得下一个祈祷时间,您需要按照本例执行以下步骤:

    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;
    }
    

    完整示例Snack

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-16
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多