Estoy tratando de obtener la fecha más cercana, que sería la próxima fecha a partir de la fecha actual, pero no sé cómo obtenerla. Traté de ordenar la matriz de listas de reservas, pero me dio la fecha anterior.
Esta es mi matriz:
const bookingsList = [ { sitterName: 'John', start: '2021-12-09', end: '2021-12-09', status: 'accepted', }, { sitterName: 'John', start: '2021-12-06', end: '2021-12-06', status: 'accepted', }, { sitterName: 'John', start: '2021-12-08', end: '2021-12-08', status: 'accepted', }, { sitterName: 'Guru', start: '2021-11-30', end: '2021-11-30', status: 'accepted', }, ]; const sortedBookings = bookingsList.sort(sortFunction); function sortFunction(a: any, b: any) { const dateA = new Date(a.start).getTime(); const dateB = new Date(b.start).getTime(); return dateA > dateB ? 1 : -1; } console.log(sortedBookings[0].start);Si tiene su matriz ordenada, puede usar la función find() para obtener el primer elemento que coincida con una condición. Y la condición podría ser elemento.fecha > Fecha.ahora(). Echa un vistazo al código:
var found = sortedBookings.find((function (element) { return new Date(element.start) > Date.now(); }));Probablemente me meteré en problemas por esto... pero aquí hay un método. Agregue la fecha de hoy en la matriz, ordénela y elija el siguiente elemento de la matriz. Luego elimine la adición de matriz. No es la mejor solución, pero te llevará a donde quieres ir.
const bookingsList = [{ sitterName: 'John', start: '2021-12-09', end: '2021-12-09', status: 'accepted', }, { sitterName: 'John', start: '2021-12-06', end: '2021-12-06', status: 'accepted', }, { sitterName: 'John', start: '2021-12-08', end: '2021-12-08', status: 'accepted', }, { sitterName: 'Guru', start: '2021-11-30', end: '2021-11-30', status: 'accepted', }, ]; let today = new Date() today = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + ("0" + today.getDate()).slice(-2); console.log('today', today); // does it exist? if (!bookingsList.find(a => a.start === today)) { bookingsList.push({ sitterName: 'deleteme', start: today }); } let sortedBookings = bookingsList.sort(sortFunction); function sortFunction(a, b) { const dateA = new Date(a.start).getTime(); const dateB = new Date(b.start).getTime(); return dateA > dateB ? 1 : -1; } let index = bookingsList.findIndex(a => a.start === today); let target = sortedBookings[(index + 1)]?.start; console.log('next date', target); // now remove the placeholder if there sortedBookings = sortedBookings.filter(a => a.sitterName !== 'deleteme'); console.log('final array', sortedBookings)