1

I'd like to find out how I can check if the current time is between 11am and 8pm in JavaScript.

Also, is there a way I can check how many minutes until 8pm from the current time?

Thanks!

Karan
  • 12,059
  • 3
  • 24
  • 40
Moody
  • 164
  • 2
  • 10
  • `moment` can be the test tool to help in your case. Here are apis you might need: https://momentjs.com/docs/#/query/is-between/, https://momentjs.com/docs/#/displaying/difference/ – tmhao2005 Jul 17 '20 at 04:44
  • 1
    Moment is rather bloated for just comparing a few dates. https://inventi.studio/en/blog/why-you-shouldnt-use-moment-js – Adrian Brand Jul 17 '20 at 05:03
  • Does this answer your question? [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – igg Jul 17 '20 at 05:03

7 Answers7

4

I think you want something like this..

checkTime();

function checkTime() {
    var date = new Date(); // current time
    var hours = date.getHours();
    var mins = date.getMinutes();
    var day = date.getDay();
    var totalMins = (hours * 60) + mins;
    var targetMins = 20 * 60
    var remainMins = targetMins - totalMins
    
    if(hours >= 11 && hours < 20) {
      document.getElementById("text").innerHTML = "Yes Current time is between 11am to 8pm And " + remainMins + " mins left to be time 8pm";
      console.log("Yes Current time is between 11am to 8pm And " + remainMins + " mins left to be time 8pm");
    }
    else {
      document.getElementById("text").innerHTML = "There is " + remainMins + " mins left to be time 8pm";
      console.log("There is " + remainMins + " mins left to be time 8pm");
    }
}
<p id="text"></p>
Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25
  • 1
    You should use `hours > =11` otherwise it will show `11:30` is `not between 11AM to 8PM`. – Karan Jul 17 '20 at 05:14
3

You can get current time with new Date().

Set hour, minute, second, milliseconds values with .setHours(11, 0, 0, 0).

You can compare it with if (fromTime <= currentTime && currentTime <= toTime) {.

toTime - currentTime will return difference in milliseconds so convert it ti minutes by dividing it with (1000*60).

Try complete code below.

function checkTime(currentTime) {
  let fromTime = new Date(currentTime).setHours(11, 0, 0, 0);
  let toTime = (new Date(currentTime)).setHours(20, 0, 0, 0);

  console.log(currentTime.toString());
  
  if (fromTime <= currentTime && currentTime <= toTime) {
    console.log('Time is between 11AM and 8PM');

    let mins = Math.ceil((toTime - currentTime) / (1000 * 60));
    console.log('Minutes left to 8PM = ' + mins);
  } else {
    console.log('Time is not between 11AM and 8PM');
  }
}

let currentTime = new Date();
checkTime(currentTime);
let customTime = new Date(2020, 10, 10, 15, 0, 0, 0);
checkTime(customTime);
Karan
  • 12,059
  • 3
  • 24
  • 40
1

Once you have a JavaScript date object, you can use the getHours method to get the hour of the day (in 24-hr time), then just compare the numbers.

To get elapsed minutes, you can subtract one date object from another, then divide by 60,000 (the number of milliseconds in a minute):

// Checks if current time is between 11am and 8pm
const
  date = new Date();
  hours = date.getHours(),
  isBetween = (hours >= 11) && (hours < 20),
  readableDate = date.toLocaleString();
console.log(`"${readableDate}" is between 11am and 8pm?: ${isBetween}`);

// Calculates minutes until 8pm
  const
    oneMinute = 60 * 1000, // JS times are measured in milliseconds
    eightPM = new Date();
  eightPM.setHours(20, 0, 0, 0); // Sets the new date object's time to 8pm
  const
    millisecsDuration = eightPM - date, // **Assumes it's before 8pm!
    minsDuration = parseInt(millisecsDuration / oneMinute);
  console.log(`Minutes until 8pm: ${minsDuration}`);
Cat
  • 4,141
  • 2
  • 10
  • 18
1

This is my approach:

function dateCompareToday() {
    const today = new Date();
    return new Date(today.setHours(11,0,0)) > today &&  today > new Date(today.setHours(20,0,0))

}

console.log(dateCompareToday())

And with parameters:

function dateCompareToday(a, b) {
    const today = new Date();
    return new Date(today.setHours(a,0,0)) > today &&  today > new Date(today.setHours(b,0,0))

}

console.log(dateCompareToday(11,20))
0

I got the time using new Date(). and then used .getHours(), .getMinutes() and .getSeconds() to get the exact time.

I then used if (hours > 11 && hours < 20) to check if it was between 11am and 8pm.

I reduced the date from endTime (endTime was 8pm) which returned the difference in milliseconds so I converted it to minutes by dividing it by (1000 * 60).

Then I just put in the result inside divs.

The divs are updating every second.

Try out my code below!

function newTime() {
  var date = new Date();

  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  if (hours > 12) {
    var hours = hours - 12;
  }
  if (hours < 10) {
    hours = "0" + hours;
  }
  if (minutes < 10) {
    minutes = "0" + minutes;
  }
  if (seconds < 10) {
    seconds = "0" + seconds;
  }

  var time = hours + ":" + minutes + ":" + seconds;
  $("#answer1").html("The time now is: " + time);
  
  hours = date.getHours();
  
  if (hours >= 11 && hours < 20) {
    $("#answer2").html("The current time is between 11am and 8pm!");
    let endTime = (new Date(date)).setHours(20, 0, 0, 0);
    let minsLeft = Math.ceil((endTime - date) / (1000 * 60));
    $("#answer3").html("Minutes left till 8pm: " + minsLeft);
  } else {
    $("#answer2").html("The current time is not between 11am and 8pm!");
  }

}

setInterval(newTime, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="answer1"></div>
<div id="answer2"></div>
<div id="answer3"></div>
topsoftwarepro
  • 773
  • 5
  • 19
  • 2
    There's a bug here. (When I looked, it said `The time now is: undefined:40:3`.) – Cat Jul 17 '20 at 05:41
  • That error is now fixed! Thank you for informing me! – topsoftwarepro Jul 17 '20 at 05:49
  • To get `padding` `0` you can use [String.prototype.padStart()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) like `hours.toString().padStart(2, "0")` – Karan Jul 17 '20 at 06:44
0

This function allows for ranges such as 10pm-4am as well

function isCurrentHourBetween(minHour, maxHour){
  if (maxHour > 23 || maxHour < 0) {
    console.error(maxHour, ' ~ Invalid Max Hour')
    return false
  }
  if (minHour > 23 || minHour < 0) {
    console.error(minHour, ' ~ Invalid Min Hour')
    return false
  }

  const currentHour = getCurrentHour() 
  // get the current hour with any of the ways listed in the other answers 
  // should be a number 0-23

  if (currentHour < 0 || currentHour > 23) {
    console.error(currentHour, ' ~ Invalid Current Hour')
    return false
  }

  if (minHour < maxHour) {
    if (currentHour >= minHour && currentHour <= maxHour) return true
    else return false
  } else if (minHour > maxHour) {
    if (currentHour >= minHour || currentHour <= maxHour) {
      return true
    } else return false
  } else {
    if (currentHour === minHour && currentHour === maxHour) return true
    else return false
  }
}
Dan P
  • 43
  • 7
-1

Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below

var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); 
var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);

console.log(check > from && check < to)
Rohan Shenoy
  • 805
  • 10
  • 23