0

I'm currently working on a break reminder. Users will be able to set start and end times which I will compare to the current times to determine when to trigger a break notification.

const currentDate = new Date();
let startTime = "09:00:00";
let endTime = "17:00:00";
const startTimeSplit = startTime.split(":");
const endTimeSplit = endTime.split(":");

const startDate = new Date();
startDate.setHours(parseInt(startTimeSplit[0], 10));
startDate.setMinutes(parseInt(startTimeSplit[1], 10));
startDate.setSeconds(0);

const endDate = new Date();
endDate.setDate(startDate.getDate() + 1)
endDate.setHours(parseInt(endTimeSplit[0], 10));
endDate.setMinutes(parseInt(endTimeSplit[1], 10));
endDate.setSeconds(0);

if (startDate <= currentDate && endDate > currentDate && this.checkNonBreakTime()) {
  const timeDelta = (currentDate.getTime() - startDate.getTime()) / 60000;
  if (timeDelta % frequency === 0) {
    this.createNotification();
  }
}

The start and end time variables are coming from a DB based on agents' preferences.

The issue here is that if the end time is potentially the next day, my code breaks.

Has anyone built a similar reminder app before and have an idea how I can go about comparing the 3 dates?

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
  • Hi, welcome to Stack Overflow! Why does your code break if the end-time is from the next day? Can you add an example of input data that breaks your code, and point out specifically what breaks? – y2bd Mar 29 '21 at 23:05
  • You could always check if the end time is before the start time and assume that means it's the next day, then [add a day](https://stackoverflow.com/questions/563406/add-days-to-javascript-date) to the end date – Phil Mar 29 '21 at 23:06
  • Tip: you can set hours, minutes, seconds and milliseconds on one go and don't need to use *parseInt*. E.g. `startDate.setHours(startTimeSplit[0], startTimeSplit[1], 0, 0)`. :-) Also consider `let [h,m,s] = startTime.split(":")` – RobG Mar 30 '21 at 00:41
  • @y2bd the code breaks when currentDate switches to the next day. startDate = new Date() will also switch since I'm only replacing the time values with times from the db – matthdan003 Mar 30 '21 at 04:15
  • @Phil that works until currentDate switches to the next day. Adding a day will more endDate a full day ahead of currentDate – matthdan003 Mar 30 '21 at 04:17
  • @RobG got it. Thanks! – matthdan003 Mar 30 '21 at 04:17

0 Answers0