1

Please, How can I set IF when time is < 21:30 ??

var dt = new Date();
if ((dt.getHours() <= 21) && (dt.getMinutes() <= 30)) { alert("check"); }

This not working when time is example 20:45

pavel
  • 26,538
  • 10
  • 45
  • 61

2 Answers2

1

You need to check two different things.

  1. if hours <= 20, than everything is true.
  2. if hours == 21, than check minutes.

var dt = new Date('2021/03/18 20:45:00');
if (dt.getHours() <= 20 || (dt.getHours() == 21 && dt.getMinutes() <= 30)) { 
    alert("check"); 
}
pavel
  • 26,538
  • 10
  • 45
  • 61
0

You could always take the time and convert it to minutes in the day - 1440 (60*24) so 21:30 becomes 21 * 60 + 30 = 1,290.

We can calculate the current minute value by taking the current date time Date.now() (milliseconds since 1/1/1970) mod 86,400,000 (milliseconds in a day) * further divide this by 60,000 (milliseconds in a minute).

(Date.now() % 86_400_000) / (60_000)

It is then trivial to compare these two values

const nineFortyFivePM = 21 * 60 + 30;
const currentMinutes = (Date.now() % 86_400_000) / (60_000);

console.log(`21:45 = ${nineFortyFivePM}`);
console.log(`currentMinutes = ${currentMinutes}`);
if (currentMinutes < nineFortyFivePM)
  alert('check');
phuzi
  • 12,078
  • 3
  • 26
  • 50