Hey everyone! I’m working on a JavaScript project to figure out how much time is left in a school period or until the next one starts. I’m having trouble with a few things though.
First I’m trying to get the current time like this:
let now = new Date();
let currentTime = now.toString().slice(16, 21);
But I’m stuck with a colon between hours and minutes. How can I fix this?
Also I’m not sure if my logic for checking if it’s during school hours is right:
if (currentTime > dayStart && currentTime < dayEnd) {
// School day logic here
} else {
console.log("School hasn't started yet");
}
I’ve got a bunch of if-else statements to check which period it is and calculate time left. Is there a better way to do this?
For your time comparison, consider using Date objects instead of strings. You can create Date objects for your period start and end times, then compare them directly with the current time. This approach is more robust and easier to work with.
As for organizing your periods, an array of objects is indeed a good suggestion. You could structure it like this:
const periods = [
{ name: 'Period 1', start: new Date().setHours(8, 0), end: new Date().setHours(9, 30) },
{ name: 'Period 2', start: new Date().setHours(9, 45), end: new Date().setHours(11, 15) },
// ... more periods ...
];
Then use Array.find() to determine the current period. This method is more maintainable and scalable than multiple if-else statements.
This approach simplified my code a lot and made it easier to maintain. You can easily add or modify periods without changing much code. Hope this helps with your project!