从数组javascript中获取最近的时间



我有一个类似的对象

var object = {
"Fajr": "04:29 (WIB)",
"Sunrise": "05:39 (WIB)",
"Dhuhr": "11:43 (WIB)",
"Asr": "14:48 (WIB)",
"Sunset": "17:48 (WIB)",
"Maghrib": "17:48 (WIB)",
"Isha": "18:53 (WIB)",
"Imsak": "04:19 (WIB)",
"Midnight": "23:43 (WIB)",
"Firstthird": "21:45 (WIB)",
"Lastthird": "01:42 (WIB)"
}

我想用矩差https://momentjs.com/docs/#/displaying/difference/。但经过几个小时的搜索,我不知道从现在起如何获得最近的时间。

例如,如果现在的时间是11:00,那么该对象的下一个时间将是11:43。我该如何做到这一点?

  1. 分析每个条目的时间并对结果进行排序
  2. 抓住后面的第一个
  3. 如果什么都没有找到,从排序的结果中获取第一个,因为它指示第二天

var object = {"Fajr":"04:29 (WIB)","Sunrise":"05:39 (WIB)","Dhuhr":"11:43 (WIB)","Asr":"14:48 (WIB)","Sunset":"17:48 (WIB)","Maghrib":"17:48 (WIB)","Isha":"18:53 (WIB)","Imsak":"04:19 (WIB)","Midnight":"23:43 (WIB)","Firstthird":"21:45 (WIB)","Lastthird":"01:42 (WIB)"};
const matcher = /d+:d+/;
const parsed = Object.entries(object)
.map(([key, time]) => {
const [hour, minute] = time.match(matcher)[0].split(":").map(Number);
const date = new Date();
date.setHours(hour, minute, 0, 0);
return { key, date };
})
.sort((a, b) => a.date - b.date);
const now = new Date();
const {key: next} = parsed.find(({ date }) => now <= date) ?? parsed[0];
console.log("next:", next, object[next]);

相关内容

  • 没有找到相关文章

最新更新