I have an object like this
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)"
}
and i want to use moment diff https://momentjs.com/docs/#/displaying/difference/ . But after searching for couple hours I don't know how to get the nearest time from now.
For example if time now is 11:00 then the time next from the object would be 11:43. How do I achieve that ?
CodePudding user response:
- Parse out the times from each entry and sort the results
- Grab the first one that comes after now
- If nothing is found, grab the first one from the sorted results as it indicates the next day
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]);