Calculating Time Remaining in School Periods with JavaScript

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?

Any help would be awesome! Thanks!

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.

hey neo, try using now.getHours() * 100 + now.getMinutes(); to avoid the colon mess.

also, maybe use an array of period objects and loop to check current period. hope it helps!

I’ve dealt with similar time-tracking challenges in my projects. Here’s what worked for me:

For getting the current time without the colon, try this:

let now = new Date();
let currentTime = now.getHours() * 100 + now.getMinutes();

This gives you a number like 1425 for 2:25 PM, which is easier to compare.

For period tracking, I found using an array of objects super helpful:

const periods = [
  { name: 'Period 1', start: 800, end: 930 },
  { name: 'Period 2', start: 945, end: 1115 },
  // Add more periods...
];

const currentPeriod = periods.find(period => currentTime >= period.start && currentTime < period.end);

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!