Estoy trabajando en un proyecto de calendario completo y me preguntaba: ¿hay alguna forma en Javascript, con un nuevo objeto Fecha, para verificar si un evento incluye un cierto período de horas?
Por ejemplo: tengo este evento que comienza a las 8:00 am y termina a las 05:00 pm, necesito ver si el período entre las 12:00 am y las 01:30 pm está incluido.
Estos son mis dos objetos Dat que captan la hora de inicio y finalización de un evento:
const starts = new Date(currentEvents[i].start._i); const ends = new Date(currentEvents[i].end._i);De hecho, cambié de método, así que gracias a todos los que intentaron darme una respuesta y dedicar tiempo a esto.
si solo compara objetos de Date , simplemente puede comparar los similares:
date1 < date2 Si eso es difícil de hacer eso, podría hacer algo como a continuación. Este código prueba si testPeriod está completamente incluido en targetPeriod .
const isTimePeriodIncluded = (targetPeriod, testPeriod) => { if (targetPeriod.start.getHours() > testPeriod.start) { return false; } if (targetPeriod.end.getHours() < testPeriod.end) { return false; } return true; }; const mydate_start = new Date(Date.now()); const mydate_end = new Date(Date.now()); mydate_end.setHours(mydate_end.getHours() + 5); //15 ~ 20 console.log( isTimePeriodIncluded( { start: mydate_start, end: mydate_end, }, { start: mydate_start.getHours() - 2, end: mydate_end.getHours() - 2, } ) ); console.log( isTimePeriodIncluded( { start: mydate_start, end: mydate_end, }, { start: mydate_start.getHours() + 2, end: mydate_end.getHours() + 2, } ) ); console.log( isTimePeriodIncluded( { start: mydate_start, end: mydate_end, }, { start: mydate_start.getHours() - 2, end: mydate_end.getHours() + 2, } ) ); console.log( isTimePeriodIncluded( { start: mydate_start, end: mydate_end, }, { start: mydate_start.getHours() + 2, end: mydate_end.getHours() - 2, } ) );No hay una función incorporada para verificar si una Date se encuentra entre 2 Date dadas, pero siempre puede implementarla. El siguiente código verifica si el período dado coincide con un límite de tiempo dado.
const ONE_MINUTE = 60000 /* Bounds */ const boundStart = new Date() // time now const boundEnd = new Date(Date.now() + (20)*ONE_MINUTE) // time now + 20mins /* Period */ const periodStart = new Date(Date.now() + (2)*ONE_MINUTE) // time now + 2mins const periodEnd = new Date(Date.now() + (10)*ONE_MINUTE) // time now + 10mins /* Below function checks for time clash */ const isFallsInBounds = (boundStart, boundEnd, periodStart, periodEnd) => { if(periodStart <= boundStart && periodEnd > boundStart) { return true } else if(periodStart > boundStart && periodStart < boundEnd) { return true } else { return false } } console.log(isFallsInBounds(boundStart, boundEnd, periodStart, periodEnd))