I'm working on a fullcalendar project and I was wondering: is there a way in Javascript, with a new Date object, to check if an event include a certain period of hours?
For example: I have this event that start at 8:00 am and end at 05:00pm, I need to see if the period between 12:00am and 01.30pm is included.
These are my two Dat objects that catch the start and end hour of an event:
const starts = new Date(currentEvents[i].start._i);
const ends = new Date(currentEvents[i].end._i);
I actually change method so thanks for everyone who tried to give me an answer and spend time for this.
if you just compare Date objects, you can simply compare the like:
date1 < date2
If that is difficult to do that, you could do something like below. This code tests whether the testPeriod is completely included in the 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,
}
)
);
There is no in-built function to check if a Date falls between 2 given Dates, but you could always implement it. The code below checks if the given period clashes with a given time bounds.
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))