-1

I want to check if current time is earlier than the time I've specified(for this example 8:20AM), so I am doing something like this:

const _MS_IN_HOUR = 1000 * 60 * 60;
const _MS_IN_MIN = 1000 * 60;

const now = new Date();
const hm = +now / _MS_IN_MIN;

if (hm <= (8 * _MS_IN_HOUR + 20 * _MS_IN_MIN)) {
  console.log("something");
}

but it's not working.

Viroz
  • 39
  • 6
  • Does this answer your question? [How to check if one date is before another date using JavaScript\JQuery?](https://stackoverflow.com/questions/27317437/how-to-check-if-one-date-is-before-another-date-using-javascript-jquery) – pilchard Nov 09 '22 at 16:40
  • 1
    convert to UNIX time then do simple less than / greater than? – Ronnie Royston Nov 09 '22 at 16:41
  • The maths are totally wrong. If you get the correct result, it's only by chance. `+now / _MS_IN_MIN` gives you the number of minutes UTC since 1 Jan 1970 (currently about 27,801,077). `(8 * _MS_IN_HOUR + 20 * _MS_IN_MIN)` gives you the number of milliseconds in 8 hours 20 minutes (30,000,000), a totally unrelated number. – RobG Nov 10 '22 at 07:16

1 Answers1

1

The OP calculation is incorrect. It compares the minutes since the ECMAScript epoch (1 Jan 1970 UTC) with the minutes represented by the supplied time.

The following checks if the supplied time is earlier that the current local time, e.g. whether it's currently after 13:15 (1:15 pm):

/* Compare time to current time, return true
 * if time is after current time, otherwise false
 * @param {string} time - H:mm format
 * @returns {boolean} true if time is after now,
 *                    otherwise false
 */
function isAfter(time) {
  let [h, m] = time.split(/\D/);
  let msToday = Date.now() - new Date().setHours(0,0,0,0);
  return msToday > (h*3.6e6 + m*6e4);
}

// True if local time is after 1:15 pm
console.log(isAfter('13:15'));
RobG
  • 142,382
  • 31
  • 172
  • 209