我正在尝试使用当前时间从数组列表中获取下一个即将到来的祈祷。
即时通信工具使用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",
},
]
谢谢你的帮助。
发布于 2021-01-31 15:37:54
你可以这样做,var json = JSON.parse(prayer); let time = json.time;我没有测试过,但这应该可以工作
发布于 2021-01-31 16:20:23
您可以使用javascript date对象来计算当前时间与每个日期之间的差。
一些粗略的代码
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])发布于 2021-01-31 17:32:42
要获得下一个祈祷时间,您需要执行以下步骤,如本例所示:
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上的完整示例
https://stackoverflow.com/questions/65976720
复制相似问题